/// <summary> /// Renders the specified React component, along with its client-side initialisation code. /// Normally you would use the <see cref="React{T}"/> method, but <see cref="ReactWithInit{T}"/> /// is useful when rendering self-contained partial views. /// </summary> /// <typeparam name="T">Type of the props</typeparam> /// <param name="htmlHelper">HTML helper</param> /// <param name="componentName">Name of the component</param> /// <param name="props">Props to initialise the component with</param> /// <param name="htmlTag">HTML tag to wrap the component in. Defaults to <div></param> /// <param name="containerId">ID to use for the container HTML tag. Defaults to an auto-generated ID</param> /// <param name="clientOnly">Skip rendering server-side and only output client-side initialisation code. Defaults to <c>false</c></param> /// <param name="containerClass">HTML class(es) to set on the container tag</param> /// <param name="exceptionHandler">A custom exception handler that will be called if a component throws during a render. Args: (Exception ex, string componentName, string containerId)</param> /// <returns>The component's HTML</returns> public static IHtmlString ReactWithInit <T>( this IHtmlHelper htmlHelper, string componentName, T props, string htmlTag = null, string containerId = null, bool clientOnly = false, string containerClass = null, Action <Exception, string, string> exceptionHandler = null ) { try { var reactComponent = Environment.CreateComponent(componentName, props, containerId, clientOnly); if (!string.IsNullOrEmpty(htmlTag)) { reactComponent.ContainerTag = htmlTag; } if (!string.IsNullOrEmpty(containerClass)) { reactComponent.ContainerClass = containerClass; } var html = reactComponent.RenderHtml(clientOnly, exceptionHandler: exceptionHandler); return(new HtmlString(html + System.Environment.NewLine + RenderToString(GetScriptTag(reactComponent.RenderJavaScript())))); } finally { Environment.ReturnEngineToPool(); } }
/// <summary> /// Renders the specified React component /// </summary> /// <typeparam name="T">Type of the props</typeparam> /// <param name="htmlHelper">HTML helper</param> /// <param name="componentName">Name of the component</param> /// <param name="props">Props to initialise the component with</param> /// <param name="htmlTag">HTML tag to wrap the component in. Defaults to <div></param> /// <param name="containerId">ID to use for the container HTML tag. Defaults to an auto-generated ID</param> /// <param name="clientOnly">Skip rendering server-side and only output client-side initialisation code. Defaults to <c>false</c></param> /// <param name="serverOnly">Skip rendering React specific data-attributes, container and client-side initialisation during server side rendering. Defaults to <c>false</c></param> /// <param name="containerClass">HTML class(es) to set on the container tag</param> /// <param name="exceptionHandler">A custom exception handler that will be called if a component throws during a render. Args: (Exception ex, string componentName, string containerId)</param> /// <returns>The component's HTML</returns> public static IHtmlString React <T>( this IHtmlHelper htmlHelper, string componentName, T props, string htmlTag = null, string containerId = null, bool clientOnly = false, bool serverOnly = false, string containerClass = null, Action <Exception, string, string> exceptionHandler = null ) { try { var reactComponent = Environment.CreateComponent(componentName, props, containerId, clientOnly, serverOnly); if (!string.IsNullOrEmpty(htmlTag)) { reactComponent.ContainerTag = htmlTag; } if (!string.IsNullOrEmpty(containerClass)) { reactComponent.ContainerClass = containerClass; } var result = reactComponent.RenderHtml(clientOnly, serverOnly, exceptionHandler); return(new HtmlString(result)); } finally { Environment.ReturnEngineToPool(); } }
public void BuildModel_Case1_StartingNodeNotInChildLevel_ShouldReturnHierarchicalNodes() { // @Html.MvcSiteMap().SiteMap(false) // Arrange var siteMap = HtmlHelperTestCases.CreateFakeSiteMapCase1(); var startingNode = siteMap.RootNode; HtmlHelper helper = new HtmlHelper(this.viewContext.Object, this.iView.Object); MvcSiteMapHtmlHelper helperExtension = new MvcSiteMapHtmlHelper(helper, siteMap, false); // Act var result = SiteMapHelper.BuildModel( helper: helperExtension, sourceMetadata: new SourceMetadataDictionary(), startingNode: startingNode, startingNodeInChildLevel: false, visibilityAffectsDescendants: true); // Assert // Tree structure - 3 nodes Assert.AreEqual("Home", result.Nodes[0].Title); Assert.AreEqual("About", result.Nodes[0].Children[0].Title); Assert.AreEqual("Contact", result.Nodes[0].Children[1].Title); // Check Counts Assert.AreEqual(1, result.Nodes.Count); Assert.AreEqual(2, result.Nodes[0].Children.Count); Assert.AreEqual(0, result.Nodes[0].Children[0].Children.Count); Assert.AreEqual(0, result.Nodes[0].Children[1].Children.Count); }
/// <summary> /// 生成bootstrap分页 /// </summary> /// <param name="helper"></param> /// <param name="page"></param> /// <param name="pagecount"></param> /// <param name="url"></param> /// <returns></returns> public static MvcHtmlString BootstrapPaging(this System.Web.Mvc.HtmlHelper helper, int page, int pagecount, string url) { var html = PagerHelper.GetPagerHtml(page, pagecount, url); return(MvcHtmlString.Create(html)); }
protected RouteData RequestingUrl(Url url) { httpContext.request.appRelativeCurrentExecutionFilePath = "~" + url.Path; httpContext.request.rawUrl = url; NameValueCollection nvc = new NameValueCollection(); foreach (var kvp in url.GetQueries()) { nvc[kvp.Key] = kvp.Value; } httpContext.request.query = nvc; foreach (var kvp in url.GetQueries()) { httpContext.request.query[kvp.Key] = kvp.Value; } var data = route.GetRouteData(httpContext); requestContext = new RequestContext(httpContext, data); urlHelper = new UrlHelper(requestContext, routes); htmlHelper = new HtmlHelper(new ViewContext { RequestContext = requestContext, HttpContext = httpContext, RouteData = requestContext.RouteData, Writer = httpContext.Response.Output }, new ViewPage(), routes); return(data); }
//Adapted from JSON.NET. public static string CamelCaseIdForModel(this System.Web.Mvc.HtmlHelper helper) { string input = helper.IdForModel().ToString(); if (string.IsNullOrEmpty(input) || !char.IsUpper(input[0])) { return(input); } var sb = new StringBuilder(); for (int i = 0; i < input.Length; ++i) { bool flag = i + 1 < input.Length; if (i == 0 || !flag || char.IsUpper(input[i + 1])) { char ch = char.ToLower(input[i], CultureInfo.InvariantCulture); sb.Append(ch); } else { sb.Append(input.Substring(i)); break; } } return(sb.ToString()); }
///<summary> /// Displays a configurable "Go To Page:" form for instances of PagedList. ///</summary> ///<param name="html">This method is meant to hook off HtmlHelper as an extension method.</param> ///<param name="list">The PagedList to use as the data source.</param> ///<param name="formAction">The URL this form should submit the GET request to.</param> ///<param name="inputFieldName">The querystring key this form should submit the new page number as.</param> ///<returns>Outputs the "Go To Page:" form HTML.</returns> public static HtmlString PagedListGoToPageForm(this System.Web.Mvc.HtmlHelper html, IPagedList list, string formAction, string inputFieldName) { return(PagedListGoToPageForm(html, list, formAction, new GoToFormRenderOptions(inputFieldName))); }
/// <summary> /// The add mobile navigation node. /// </summary> /// <param name="htmlHelper"> /// The html helper. /// </param> /// <param name="node"> /// The node. /// </param> /// <param name="dataTheme"> /// The data theme. /// </param> /// <param name="dataContentTheme"> /// The data content theme. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string AddMobileNavigationNode( HtmlHelper htmlHelper, NavigationNode node, string dataTheme, string dataContentTheme) { var nodeOutput = new StringBuilder(); if (node.Children.Count > 0) { nodeOutput.Append( string.Format( "<div data-role=\"collapsible\" data-theme=\"{0}\" data-content-theme=\"{1}\">", dataTheme, dataContentTheme)); } if (node.Children.Count == 0) { nodeOutput.Append( htmlHelper.ActionLink( node.Name, node.Action, node.Controller, null, new { data_role = "button", rel = "external" })); } else { nodeOutput.Append(AddMobileSubMenu(htmlHelper, node.Children)); } if (node.Children.Count > 0) { nodeOutput.Append("</div>"); } return nodeOutput.ToString(); }
public static string RenderFormGroupRadioButton(HtmlHelper html, RadioButtonModel inputModel, LabelModel labelModel) { var validationMessage = ""; var radioType = "form-icon"; if (inputModel.displayValidationMessage) { var validation = html.ValidationMessage(inputModel.htmlFieldName).ToHtmlString(); validationMessage = new HelpText(validation, inputModel.validationMessageStyle).ToHtmlString(); } if (labelModel == null && inputModel.RadioType != InputRadioCheckBoxType._NotSet) radioType = inputModel.RadioType.ToName(); var label = RenderLabel(html, labelModel ?? new LabelModel { htmlFieldName = inputModel.htmlFieldName, metadata = inputModel.metadata, innerInputType = InputType.Radio, innerInputModel = inputModel, innerValidationMessage = validationMessage, htmlAttributes = new {@class = $"form-radio {radioType} form-text"}.ToDictionary() }); var fieldIsValid = true; if (inputModel != null) fieldIsValid = html.ViewData.ModelState.IsValidField(inputModel.htmlFieldName); return new FormGroup(null, label, FormGroupType.CheckBoxLike, fieldIsValid).ToHtmlString(); }
public void Init() { var context = Substitute.For <ViewContext>(); var container = Substitute.For <IViewDataContainer>(); this._htmlHelper = new System.Web.Mvc.HtmlHelper(context, container); }
protected ModelRendererBase(HtmlHelper html, object model) { this.htmlHelper = html; this.model = model; this.htmlTextWriter = new HtmlTextWriter(new StringWriter()); }
public static string AddNavigationNode(HtmlHelper htmlHelper, NavigationNode node) { StringBuilder nodeOutput = new StringBuilder(); if (node.Children.Count == 0) { nodeOutput.Append("<li>"); } else { nodeOutput.Append("<li class=\"dropdown\">"); } if (node.Children.Count == 0) { nodeOutput.Append(htmlHelper.ActionLink(node.Name, node.Action, node.Controller).ToString()); } else { nodeOutput.Append(string.Format(@"<a href=""#"" class=""dropdown-toggle"" data-toggle=""dropdown"">{0}<b class=""caret""></b></a>", node.Name)); nodeOutput.Append(AddSubMenu(htmlHelper, node.Children)); } nodeOutput.Append("</li>"); return nodeOutput.ToString(); }
public HtmlHelperExtensionsTests() { var context = A.Fake<ViewContext>(); var container = A.Fake<IViewDataContainer>(); _helper = new HtmlHelper(context, container); }
public ButtonTests() { var viewContext = new Mock<ViewContext>(); var viewDataContainer = new Mock<IViewDataContainer>(); _html = new HtmlHelper(viewContext.Object, viewDataContainer.Object); }
public MenuWriter(HtmlHelper htmlHelper, Menu menu, bool nest, object attributes) { this.htmlHelper = htmlHelper; this.menu = menu; this.nest = nest; this.attributes = attributes; }
///<summary> /// Displays a configurable "Go To Page:" form for instances of PagedList. ///</summary> ///<param name="html">This method is meant to hook off HtmlHelper as an extension method.</param> ///<param name="list">The PagedList to use as the data source.</param> ///<param name="formAction">The URL this form should submit the GET request to.</param> ///<param name="options">Formatting options.</param> ///<returns>Outputs the "Go To Page:" form HTML.</returns> public static MvcHtmlString PagedListGoToPageForm(this System.Web.Mvc.HtmlHelper html, IPagedList list, string formAction, GoToFormRenderOptions options) { var form = new TagBuilder("form"); form.AddCssClass("PagedList-goToPage"); form.Attributes.Add("action", formAction); form.Attributes.Add("method", "get"); var fieldset = new TagBuilder("fieldset"); var label = new TagBuilder("label"); label.Attributes.Add("for", options.InputFieldName); label.SetInnerText(options.LabelFormat); var input = new TagBuilder("input"); input.Attributes.Add("type", options.InputFieldType); input.Attributes.Add("name", options.InputFieldName); input.Attributes.Add("value", list.PageNumber.ToString()); var submit = new TagBuilder("input"); submit.Attributes.Add("type", "submit"); submit.Attributes.Add("value", options.SubmitButtonFormat); fieldset.InnerHtml = label.ToString(); fieldset.InnerHtml += input.ToString(TagRenderMode.SelfClosing); fieldset.InnerHtml += submit.ToString(TagRenderMode.SelfClosing); form.InnerHtml = fieldset.ToString(); return(new MvcHtmlString(form.ToString())); }
public static HtmlString RenderCheckBoxCustom(HtmlHelper html, CheckBoxModel model) { var fullHtmlFieldName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(model.htmlFieldName); model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata)); ModelState modelState; if (html.ViewData.ModelState.TryGetValue(fullHtmlFieldName, out modelState)) { if (modelState.Errors.Count > 0) model.htmlAttributes.AddOrMergeCssClass("class", "input-validation-error"); if (modelState.Value != null && ((string[]) modelState.Value.RawValue).Contains(model.value.ToString())) model.isChecked = true; } var input = new TagBuilder("input"); input.Attributes.Add("type", "checkbox"); input.Attributes.Add("name", fullHtmlFieldName); input.Attributes.Add("id", model.id); input.Attributes.Add("value", model.value.ToString()); if (model.isChecked) input.Attributes.Add("checked", "checked"); if (model.isDisabled) input.Attributes.Add("disabled", "disabled"); input.MergeAttributes(model.htmlAttributes.FormatHtmlAttributes()); return new HtmlString(input.ToString(TagRenderMode.SelfClosing)); }
/// <summary> /// Renders the fieldset partial /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="fieldsetModel"></param> /// <param name="partialPath">The partial path.</param> /// <param name="viewDataDictionary">The view data dictionary.</param> /// <returns></returns> private static IHtmlString RenderPartial(HtmlHelper htmlHelper, ArchetypeFieldsetModel fieldsetModel, string partialPath, ViewDataDictionary viewDataDictionary) { var context = HttpContext.Current; if (fieldsetModel == null || context == null) { return new HtmlString(""); } var sb = new StringBuilder(); var pathToPartials = "~/Views/Partials/Archetype/"; if (!string.IsNullOrEmpty(partialPath)) { pathToPartials = partialPath; } var partial = pathToPartials + fieldsetModel.Alias + ".cshtml"; if (System.IO.File.Exists(context.Server.MapPath(partial))) { sb.AppendLine(htmlHelper.Partial(partial, fieldsetModel, viewDataDictionary).ToString()); } else { LogHelper.Info<ArchetypeModel>(string.Format("The partial for {0} could not be found. Please create a partial with that name or rename your alias.", context.Server.MapPath(partial))); } return new HtmlString(sb.ToString()); }
public RibbonAppMenu(HtmlHelper helper, string id, string title, string iconUrl = null) : base(helper) { Id = id; Title = title; IconUrl = iconUrl; }
public MvcHtmlString ComponentPresentations(IPage tridionPage, HtmlHelper htmlHelper, string[] includeComponentTemplate, string includeSchema) { LoggerService.Information(">>ComponentPresentations", LoggingCategory.Performance); StringBuilder sb = new StringBuilder(); foreach (IComponentPresentation cp in tridionPage.ComponentPresentations) { if (includeComponentTemplate != null && !MustInclude(cp.ComponentTemplate, includeComponentTemplate)) continue; if (cp.Component != null && (!string.IsNullOrEmpty(includeSchema)) && !MustInclude(cp.Component.Schema, includeSchema)) continue; // Quirijn: if a component presentation was created by a non-DD4T template, its output was stored in RenderedContent // In that case, we simply write it out // Note that this type of component presentations cannot be excluded based on schema, because we do not know the schema if (!string.IsNullOrEmpty(cp.RenderedContent)) return new MvcHtmlString(cp.RenderedContent); LoggerService.Debug("rendering cp {0} - {1}", LoggingCategory.Performance, cp.Component.Id, cp.ComponentTemplate.Id); cp.Page = tridionPage; LoggerService.Debug("about to call RenderComponentPresentation", LoggingCategory.Performance); if (ShowAnchors) sb.Append(string.Format("<a id=\"{0}\"></a>", DD4T.Utils.TridionHelper.GetLocalAnchor(cp))); sb.Append(RenderComponentPresentation(cp, htmlHelper)); LoggerService.Debug("finished calling RenderComponentPresentation", LoggingCategory.Performance); } LoggerService.Information("<<ComponentPresentations", LoggingCategory.Performance); return MvcHtmlString.Create(sb.ToString()); }
public static string RenderFormGroupCustom(HtmlHelper html, FormGroupCustomModel customModel, LabelModel labelModel) { var label = RenderControl.RenderLabel(html, labelModel ?? new LabelModel { htmlFieldName = labelModel.htmlFieldName, metadata = labelModel.metadata, htmlAttributes = new { @class = "control-label" }.ToDictionary() }); var htmlInput = customModel.input; TagBuilder wrapper = null; if (!string.IsNullOrEmpty(customModel.controlsElementWrapper)) { wrapper = new TagBuilder(customModel.controlsElementWrapper); if (customModel.controlsElementWrapperAttributes != null) wrapper.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(customModel.controlsElementWrapperAttributes)); wrapper.InnerHtml = htmlInput.ToHtmlString(); } HtmlString htmlString = wrapper != null ? new HtmlString(wrapper.ToString(TagRenderMode.Normal)) : htmlInput; bool fieldIsValid = true; if (labelModel != null && labelModel.htmlFieldName != null) fieldIsValid = html.ViewData.ModelState.IsValidField(labelModel.htmlFieldName); return new FormGroup(htmlString, label, FormGroupType.TextBoxLike, fieldIsValid).ToHtmlString(); }
public HiggsLabel(HtmlHelper helper, ControlBase input, string text) : base(helper, "label") { ForInputId = input.Id; Text = text; input.OnIdChange += MainInput_OnChangeId; }
private static IDictionary<string, MvcHtmlString> GetFlashMessages(HtmlHelper helper, string sessionKey) { sessionKey = "Flash." + sessionKey; return (helper.ViewContext.TempData[sessionKey] != null ? (IDictionary<string, MvcHtmlString>)helper.ViewContext.TempData[sessionKey] : new Dictionary<string, MvcHtmlString>()); }
public IHtmlString GetHtml(HtmlHelper htmlHelper, string themeName) { var builder = htmlHelper.Telerik().StyleSheetRegistrar(); var themeInfo = GetThemeInfo(themeName); if (themeInfo.EnableCommonCss) { builder.DefaultGroup(i => i.Add("~/Content/common.css")); } var themePath = GetThemePath(themeName); foreach (var file in themeInfo.CssFiles) { builder.DefaultGroup(i => i.Add(string.Format("{0}/{1}", themePath, file))); } if (_site.EnableCustomCss) { var customCssPath = _site.GetCustomCssPath(); if (File.Exists(HttpContext.Current.Server.MapPath(customCssPath))) { builder.DefaultGroup(i => i.Add(customCssPath)); } } builder.DefaultGroup(i => i.Combined(true).Compress(true)); return new MvcHtmlString(builder.ToHtmlString()); }
public void Setup() { // WikiController setup (use WikiController as it's the one typically used by views) _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _context = _container.UserContext; _pageRepository = _container.PageRepository; _pluginFactory = _container.PluginFactory; _settingsService = _container.SettingsService; _userService = _container.UserService; _historyService = _container.HistoryService; _pageService = _container.PageService; _wikiController = new WikiController(_applicationSettings, _userService, _pageService, _context, _settingsService); _wikiController.SetFakeControllerContext("~/wiki/index/1"); // HtmlHelper setup var viewDataDictionary = new ViewDataDictionary(); _viewContext = new ViewContext(_wikiController.ControllerContext, new Mock<IView>().Object, viewDataDictionary, new TempDataDictionary(), new StringWriter()); var mockViewDataContainer = new Mock<IViewDataContainer>(); mockViewDataContainer.Setup(v => v.ViewData).Returns(viewDataDictionary); _htmlHelper = new HtmlHelper(_viewContext, mockViewDataContainer.Object); }
/// <summary> /// </summary> /// <param name="siteMapPermission"></param> /// <param name="mainMenu"></param> /// <param name="maxLevel"></param> /// <param name="currentLevel"></param> /// <returns>return true main this menu is active.</returns> private static void SubMenuMatch(HtmlHelper helper, SiteMapPermission siteMapPermission, MainMenu mainMenu, int maxLevel, int currentLevel) { for (int i = 0; i < mainMenu.Current.ChildNodes.Count; i++) { ISiteMapNode childNode = mainMenu.Current.ChildNodes[i]; string a = childNode.Title; if (Match(siteMapPermission, childNode)) //�������disabled { var childMainMenu = new MainMenu { Current = childNode, }; mainMenu.SubMenus.Add(childMainMenu); if (currentLevel + 1 <= maxLevel) { SubMenuMatch(helper, siteMapPermission, childMainMenu, maxLevel, currentLevel + 1); if (childMainMenu.Current.Equals(helper.MvcSiteMap().SiteMap.CurrentNode)) { childMainMenu.Actived = true; mainMenu.Actived = true; } } } } }
public static HtmlString AddInfoModalWindow(HtmlHelper helper, string headText, string bodyText) { var script = "<script type='text/javascript'>" + "$(function () { $('#modalWindow').modal('toggle');});" + "</script>"; var result = "<div id='modalWindow' class='modal fade in' role='dialog' style='display: block !important'>" + "<div class='modal-dialog'>" + "<div class='modal-content'>" + "<div class='modal-header'>" + "<button type='button' class='close' data-dismiss='modal'>×</button>" + "<h4 class='modal-title'>" + headText + "</h4>" + "</div>" + "<div class='modal-body'>" + "<p>" + bodyText + "</p>" + "</div>" + "<div class='modal-footer'>" + "<button type='button' class='btn btn-default' data-dismiss='modal'>Ok</button>" + "</div>" + "</div>" + "</div>" + "</div>"; return new HtmlString(script + result); }
public static HtmlHelper Create() { var viewContext = new ViewContext(); var dataContainer = new Mock<IViewDataContainer>(); var htmlHelper = new HtmlHelper(viewContext, dataContainer.Object); return htmlHelper; }
public static HtmlString AddActionModalWindow(HtmlHelper helper, string headText, string bodyText, string actionName, string controlName, object paramsList, string applyButtonName, string id) { var a = helper.ActionLink(applyButtonName, actionName, controlName, paramsList, new { @class = "btn btn-default", @id = "CauseLink" }); var result = "<div id='modalWindow" + id + "' class='modal fade' role='dialog'>" + "<div class='modal-dialog'>" + "<div class='modal-content'>" + "<div class='modal-header'>" + "<button type='button' class='close' data-dismiss='modal'>×</button>" + "<h4 class='modal-title'>" + headText + "</h4>" + "</div>" + "<div class='modal-body'>" + "<p>" + bodyText + "</p>" + "</div>" + "<div class='modal-footer'>" + "<button type='button' class='btn btn-default' data-dismiss='modal'>Отмена</button>" + a.ToString() + "</div>" + "</div>" + "</div>" + "</div>"; return new HtmlString(result); }
public static string RenderFormGroupSelectElement(HtmlHelper html, SelectElementModel inputModel, LabelModel labelModel, InputType inputType) { HtmlString input = null; if (inputType == InputType.DropDownList) input = RenderSelectElement(html, inputModel, InputType.DropDownList); if (inputType == InputType.ListBox) input = RenderSelectElement(html, inputModel, InputType.ListBox); var label = RenderLabel(html, labelModel ?? new LabelModel { htmlFieldName = inputModel.htmlFieldName, metadata = inputModel.metadata, htmlAttributes = new {@class = "control-label"}.ToDictionary() }); var fieldIsValid = true; if (inputModel != null) fieldIsValid = html.ViewData.ModelState.IsValidField(inputModel.htmlFieldName); return new FormGroup(input, label, FormGroupType.TextBoxLike, fieldIsValid).ToHtmlString(); }
private static string GenerateUrl(HtmlHelper htmlHelper, Route route, RouteValueDictionary routeValues) { //TODO: remove code dupe see UrlLinkToExtensions var requestCtx = htmlHelper.ViewContext.RequestContext; var httpCtx = requestCtx.HttpContext; if (routeValues != null) { foreach (var d in route.Defaults) { if (!routeValues.ContainsKey(d.Key)) routeValues.Add(d.Key, d.Value); } } else { routeValues = route.Defaults; } VirtualPathData vpd = route.GetVirtualPath(requestCtx, routeValues); if (vpd == null) return null; return httpCtx.Request.ApplicationPath + vpd.VirtualPath; }
public void RenderMainNav_RendersTheRootNodes() { var mockContainer = new Mock<IViewDataContainer>(); var helper = new HtmlHelper( new ViewContext(), mockContainer.Object ); string result = helper.RenderMainNav( "Admin", new { @class = "myNav", id = "menu" } ); Assert.AreEqual( "<ul class='myNav' id='menu' ><li><a href='/Home/Index' title=HOME>HOME</a></li>\r\n<li><a href='/Dashboard/Index' title=Dashboard>Dashboard</a></li>\r\n<li><a href='/Administrator/Stats' title=My Stats>My Stats</a></li>\r\n</ul>", result ); }
public void Grid_GridSettingsIsNull_EmptyHtmlString() { var html = new HtmlHelper(new ViewContext(), new ViewDataContainer()); MvcHtmlString grid = html.Grid(null); Assert.AreEqual(string.Empty, grid.ToString()); }
public ViewComponentFactory(HtmlHelper htmlHelper, IUrlGenerator urlGenerator) : base(htmlHelper.ViewContext) { Guard.IsNotNull(urlGenerator, "urlGenerator"); this.urlGenerator = urlGenerator; }
/// <summary> /// Create a new HtmlHelper with a fake context and container /// </summary> /// <returns>HtmlHelper</returns> public static HtmlHelper Create() { var vc = new ViewContext(); vc.HttpContext = new FakeHttpContext(); var html = new HtmlHelper(vc, new FakeViewDataContainer()); return html; }
public string GenerateTab(ref HtmlHelper html, string text, string value) { var routeDataValues = html.ViewContext.RequestContext.RouteData.Values; RouteValueDictionary pageLinkValueDictionary = new RouteValueDictionary { { Param, value } }; if (html.ViewContext.RequestContext.HttpContext.Request.QueryString["search"] != null) pageLinkValueDictionary.Add("search", html.ViewContext.RequestContext.HttpContext.Request.QueryString["search"]); if (!pageLinkValueDictionary.ContainsKey("id") && routeDataValues.ContainsKey("id")) pageLinkValueDictionary.Add("id", routeDataValues["id"]); // To be sure we get the right route, ensure the controller and action are specified. if (!pageLinkValueDictionary.ContainsKey("controller") && routeDataValues.ContainsKey("controller")) pageLinkValueDictionary.Add("controller", routeDataValues["controller"]); if (!pageLinkValueDictionary.ContainsKey("action") && routeDataValues.ContainsKey("action")) pageLinkValueDictionary.Add("action", routeDataValues["action"]); // 'Render' virtual path. var virtualPathForArea = RouteTable.Routes.GetVirtualPathForArea(html.ViewContext.RequestContext, pageLinkValueDictionary); if (virtualPathForArea == null) return null; var stringBuilder = new StringBuilder("<li"); if (value == CurrentValue) stringBuilder.Append(" class=active"); stringBuilder.AppendFormat("><a href={0}>{1}</a></li>", virtualPathForArea.VirtualPath, text); return stringBuilder.ToString(); }
/// <summary> /// Render a React StaticRouter Component with context object. /// Can optionally be provided with a custom context handler to handle the various status codes. /// </summary> /// <param name="htmlHelper">MVC Razor <see cref="IHtmlHelper"/></param> /// <param name="componentName">Name of React Static Router component. Expose component globally to ReactJS.NET</param> /// <param name="props">Props to initialise the component with</param> /// <param name="path">F.x. from Request.Path. Used by React Static Router to determine context and routing.</param> /// <param name="contextHandler">Optional custom context handler, can be used instead of providing a Response object</param> /// <param name="htmlTag">HTML tag to wrap the component in. Defaults to <div></param> /// <param name="containerId">ID to use for the container HTML tag. Defaults to an auto-generated ID</param> /// <param name="clientOnly">Skip rendering server-side and only output client-side initialisation code. Defaults to <c>false</c></param> /// <param name="serverOnly">Skip rendering React specific data-attributes during server side rendering. Defaults to <c>false</c></param> /// <param name="containerClass">HTML class(es) to set on the container tag</param> /// <returns><see cref="IHtmlString"/> containing the rendered markup for provided React Router component</returns> public static IHtmlString ReactRouterWithContext <T>( this IHtmlHelper htmlHelper, string componentName, T props, string path = null, string htmlTag = null, string containerId = null, bool clientOnly = false, bool serverOnly = false, string containerClass = null, Action <HttpResponse, RoutingContext> contextHandler = null ) { try { var response = htmlHelper.ViewContext.HttpContext.Response; path = path ?? htmlHelper.ViewContext.HttpContext.Request.Path; var reactComponent = Environment.CreateRouterComponent( componentName, props, path, containerId, clientOnly ); if (!string.IsNullOrEmpty(htmlTag)) { reactComponent.ContainerTag = htmlTag; } if (!string.IsNullOrEmpty(containerClass)) { reactComponent.ContainerClass = containerClass; } var executionResult = reactComponent.RenderRouterWithContext(clientOnly, serverOnly); if (executionResult.Context?.status != null) { // Use provided contextHandler if (contextHandler != null) { contextHandler(response, executionResult.Context); } // Handle routing context internally else { SetServerResponse.ModifyResponse(executionResult.Context, response); } } return(new HtmlString(executionResult.RenderResult)); } finally { Environment.ReturnEngineToPool(); } }
public static FormVm FormForAction <TController, TArg1, TArg2, TArg3, TArg4, TArg5, TActionResult>( this System.Web.Mvc.HtmlHelper html, Expression <Func <TController, TArg1, TArg2, TArg3, TArg4, TArg5, TActionResult> > action) where TController : IController where TActionResult : ActionResult { return(FormFor(html, action.MethodInfo())); }
public virtual void NotifyWarning(string message) { TempData["NotifyWarning"] = HtmlHelper.Vertex().Popup() .AutoShow() .Message(message) .BgColor(Utilities.BootstrapColor.Warning) .ToHtmlString(); }
public static IHtmlString Rating(this System.Web.Mvc.HtmlHelper html, ProductRating rating) { if (rating == null || rating.ReviewCount == 0) { return(new MvcHtmlString("<span><em>No Rating</em></span>")); } return(html.Partial("_Rating", rating)); }
public override System.Web.Mvc.MvcHtmlString WriteFilter(System.Web.Mvc.HtmlHelper helper, object htmlAttributes) { IDictionary <string, object> efHtmlAttributes = new RouteValueDictionary(htmlAttributes); AddCommonHtmlAttributes(efHtmlAttributes); return(helper.Partial(PartialViewName, this)); }
public static IHtmlString File(this System.Web.Mvc.HtmlHelper helper, string id) { TagBuilder tb = new TagBuilder("input"); tb.Attributes.Add("type", "file"); tb.Attributes.Add("id", id); return(new MvcHtmlString(tb.ToString())); }
public static MvcHtmlString BootstrapSubmit( this System.Web.Mvc.HtmlHelper html, string value, ContextualColor contextualColor) { return(MvcHtmlString.Create( $"<input class=\"btn btn-{ContextualColors[contextualColor]}\" type=\"submit\" value =\"{value}\"/>")); }
/// <summary> /// Sịnh động Trạng thái /// </summary> /// <param name="status"></param> /// <returns></returns> public static MvcHtmlString RenderStatus(this HtmlHelper html, int status) { //DacPV TODO TagBuilder tag = new TagBuilder("lable"); tag.MergeAttribute("value", status.ToString()); return(new MvcHtmlString("Trạng thái " + tag.ToString())); }
public static MvcHtmlString DeliveredLink(this HtmlHelper htmlHelper, OrderView model) { if (model.CanFinishDelivery) { return(htmlHelper.ActionLink("Delivered", "Delivery", "Order", new { id = model.ID }, null)); } return(MvcHtmlString.Empty); }
public static IHtmlContent RenderVendrReviews(this IHtmlHelper html, string partialViewPath, Guid storeId, string productReference) { return(html.Partial(partialViewPath, new ViewDataDictionary(html.ViewData) { { "storeId", storeId }, { "productReference", productReference } })); }
public static MvcHtmlString CreateProductLink(this HtmlHelper htmlHelper, OrderView model) { if (model.CanCreateProduct) { return(htmlHelper.ActionLink("Create New", "Create", "Product", new { id = model.ID }, null)); } return(MvcHtmlString.Empty); }
public void Setup() { _autoSubstitute = AutoSubstituteContainer.Create(); _h = _autoSubstitute.ResolveAndSubstituteFor<HtmlHelper<TestFieldViewModel>>(); _t = _autoSubstitute.Resolve<IFormTemplate>(); _t.BeginForm(Action, Method, _htmlAttributes, Enctype).Returns(_beginHtml); _t.EndForm().Returns(_endHtml); }
public static MvcHtmlString PassToRestaurantLink(this HtmlHelper htmlHelper, OrderView model) { if (model.CanPassToRestaurant) { return(htmlHelper.ActionLink("Passed to restaurant", "Restaurant", "Order", new { id = model.ID }, null)); } return(MvcHtmlString.Empty); }
public void Should_Render_Hidden_Submit_Button() { IHtmlString button = new HtmlHelper(new ViewContext(), new ViewPage()).HiddenSubmit(); string html = button.ToHtmlString().Trim(); Assert.IsTrue(html.StartsWith("<input ")); Assert.IsTrue(html.EndsWith("/>")); Assert.IsTrue(html.Contains("display:none") || html.Contains("display: none")); }
public static string Localize <T>(this HtmlHelper htmlHelper, T source) where T : struct { var key = $"{typeof(T).Name}.{source}"; var translationService = HttpContext.Current.GetService <IIntranetLocalizationService>(); return(translationService.Translate(key)); }
public static ValidationType GetValidationType <TModel, TProperty>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TProperty> > expression) { var expressionText = ExpressionHelper.GetExpressionText(expression); var htmlFieldPrefix = helper.ViewData.TemplateInfo.HtmlFieldPrefix; var propertyName = string.IsNullOrEmpty(htmlFieldPrefix) ? expressionText : string.Join(".", htmlFieldPrefix, expressionText); return(GetValidationType(helper, propertyName)); }
public static MvcHtmlString Title(this HtmlHelper html, params string[] titleParts) { var pageTitleBuilder = html.GetWorkContext().Resolve <IPageTitleBuilder>(); html.AddTitleParts(titleParts); return(MvcHtmlString.Create(html.Encode(pageTitleBuilder.GenerateTitle()))); }
/// <summary> /// /// </summary> /// <param name="helper"></param> /// <param name="metadata"></param> /// <param name="fieldName"></param> /// <param name="minDate"></param> /// <param name="maxDate"></param> private static string DatePickerForHelper(System.Web.Mvc.HtmlHelper helper, ModelMetadata metadata, string fieldName, DateTime?minDate = null, DateTime?maxDate = null) { // Validate the model type is DateTime or Nullable<DateTime> if (!(metadata.Model is DateTime || Nullable.GetUnderlyingType(metadata.ModelType) == typeof(DateTime))) { throw new ArgumentException(string.Format(_NotADate, fieldName)); } // Validate dates if (minDate.HasValue && maxDate.HasValue && minDate.Value >= maxDate.Value) { throw new ArgumentException("The minimum date cannot be greater than the maximum date"); } if (minDate.HasValue && metadata.Model != null && (DateTime)metadata.Model < minDate.Value) { throw new ArgumentException("The date cannot be less than the miniumum date"); } if (maxDate.HasValue && metadata.Model != null && (DateTime)metadata.Model > maxDate.Value) { throw new ArgumentException("The date cannot be greater than the maximum date"); } // Construct date picker StringBuilder html = new StringBuilder(); // Add display text html.Append(DatePickerText(metadata)); // Add input html.Append(DatePickerInput(helper, metadata, fieldName)); // Add drop button html.Append(ButtonHelper.DropButton()); // Get the default date to display DateTime date = DateTime.Today; bool isSelected = false; // If a date has been provided, use it and mark it as selected if (metadata.Model != null) { date = (DateTime)metadata.Model; isSelected = true; } // Add calendar html.Append(Calendar(date, isSelected, minDate, maxDate)); // Build container System.Web.Mvc.TagBuilder container = new System.Web.Mvc.TagBuilder("div"); container.AddCssClass("datepicker-container"); // Add min and max date attributes if (minDate.HasValue) { container.MergeAttribute("data-mindate", string.Format("{0:d/M/yyyy}", minDate.Value)); } if (maxDate.HasValue) { container.MergeAttribute("data-maxdate", string.Format("{0:d/M/yyyy}", maxDate.Value)); } container.InnerHtml = html.ToString(); // Return the html return(container.ToString());; }
public static System.Web.WebPages.HelperResult TableHeader(System.Web.Mvc.HtmlHelper helper, PropertyMetadata prop, string title, TableHelpers.SortOrder sortOrder) { #line default #line hidden return(new System.Web.WebPages.HelperResult(__razor_helper_writer => { if (prop.Sortable) { WriteLiteralTo(__razor_helper_writer, " <th"); WriteLiteralTo(__razor_helper_writer, " class=\"sortable\""); WriteLiteralTo(__razor_helper_writer, " data-name=\""); WriteTo(__razor_helper_writer, prop.PropertyInfo.Name); WriteLiteralTo(__razor_helper_writer, "\""); WriteLiteralTo(__razor_helper_writer, " data-descending=\""); WriteTo(__razor_helper_writer, TableHelpers.IsOppositeOrderDescending(sortOrder).ToString()); WriteLiteralTo(__razor_helper_writer, "\""); WriteLiteralTo(__razor_helper_writer, ">\r\n <div"); WriteLiteralTo(__razor_helper_writer, " class=\"sortable\""); WriteLiteralTo(__razor_helper_writer, ">\r\n"); WriteLiteralTo(__razor_helper_writer, " "); WriteTo(__razor_helper_writer, title); WriteLiteralTo(__razor_helper_writer, "\r\n <span"); WriteAttributeTo(__razor_helper_writer, "class", Tuple.Create(" class=\"", 3801), Tuple.Create("\"", 3848) , Tuple.Create(Tuple.Create("", 3809), Tuple.Create("fa", 3809), true) , Tuple.Create(Tuple.Create(" ", 3811), Tuple.Create <System.Object, System.Int32>(TableHelpers.GetSortIcon(sortOrder) , 3812), false) ); WriteLiteralTo(__razor_helper_writer, " style=\"margin-right: 5px\""); WriteLiteralTo(__razor_helper_writer, "></span>\r\n </div>\r\n </th>\r\n"); } else { WriteLiteralTo(__razor_helper_writer, " <th>"); WriteTo(__razor_helper_writer, title); WriteLiteralTo(__razor_helper_writer, "</th>\r\n"); } })); #line default #line hidden }
/// <summary> /// 为 <see cref="HtmlHelper"/> 对象扩展 linkbutton 元素。 /// </summary> /// <param name="htmlHelper"></param> /// <param name="id">ID 属性值。</param> /// <param name="onClick">单击时执行的 js 脚本。</param> /// <param name="settings">参数选项。</param> /// <returns></returns> public static HtmlString LinkButton(this System.Web.Mvc.HtmlHelper htmlHelper, string id, string onClick, LinkButtonSettings settings = null) { var builder = new TagBuilder("span"); builder.AddCssClass("easyui-linkbutton"); builder.MergeAttribute("data-options", SettingsSerializer.Serialize(settings)); builder.GenerateId(id); return(new HtmlString(builder.ToString(TagRenderMode.Normal))); }
public static MvcHtmlString GetSortingUrl <T>(this System.Web.Mvc.HtmlHelper html, Paging.PagedResult <T> pagedResult, string propertyName, string url) { string extendedUrl = url .SetParameter("sortColumn", propertyName) .SetParameter("sortDirection", GetSortDirection(pagedResult.Paging, propertyName).ToString()) .SetParameter("pageIndex", "0"); return(MvcHtmlString.Create(extendedUrl)); }
/// <summary> /// Renders the <img> tag. /// </summary> /// <param name="htmlHelper"><c>HtmlHelper</c> instance.</param> /// <param name="src">Image file location.</param> /// <param name="imageAttributes">List of attributes for the {img} tag.</param> /// <returns>Returns the <img> tag in HTML format.</returns> public static MvcHtmlString Image(this System.Web.Mvc.HtmlHelper htmlHelper, string src, object imageAttributes) { if (String.IsNullOrWhiteSpace(src)) { throw new ArgumentNullException("src"); } return(Image(htmlHelper, src, System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(imageAttributes))); }
public static IHtmlString RenderBBCode(this System.Web.Mvc.HtmlHelper html, string bbcode) { if (String.IsNullOrEmpty(bbcode)) { return(html.Raw("")); } bbcode = bbcode.Replace("\n", "[br]"); return(html.Raw(DefaultBBCodeParser.ToHtml(bbcode))); }
public static IHtmlString Image(this System.Web.Mvc.HtmlHelper helper, string src, string alt) { TagBuilder tb = new TagBuilder("img"); tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src)); tb.Attributes.Add("alt", alt); return(new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing))); }