public static MvcHtmlString ImageActionLink( this HtmlHelper helper, string imageUrl, string altText, string actionName, string controllerName, object routeValues, object linkHtmlAttributes, object imgHtmlAttributes) { var linkAttributes = AnonymousObjectToKeyValue(linkHtmlAttributes); var imgAttributes = AnonymousObjectToKeyValue(imgHtmlAttributes); var imgBuilder = new TagBuilder("img"); imgBuilder.MergeAttribute("src", imageUrl); imgBuilder.MergeAttribute("alt", altText); imgBuilder.MergeAttributes(imgAttributes, true); var urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection); var linkBuilder = new TagBuilder("a"); linkBuilder.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues)); linkBuilder.MergeAttributes(linkAttributes, true); var text = linkBuilder.ToString(TagRenderMode.StartTag); text += imgBuilder.ToString(TagRenderMode.SelfClosing); text += linkBuilder.ToString(TagRenderMode.EndTag); return MvcHtmlString.Create(text); }
public static HtmlString Foo(this HtmlHelper h, string attr, string id, string tagElement) { var tBuilder = new TagBuilder(tagElement); tBuilder.GenerateId(attr + id); var c = new HtmlString(tBuilder.ToString()); return c; }
public static MvcHtmlString Css(this HtmlHelper helper, string file, string mediaType) { if (String.IsNullOrEmpty(file)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "file"); } string src; if (ScriptExtensions.IsRelativeToDefaultPath(file)) { src = "~/Content/" + file; } else { src = file; } TagBuilder linkTag = new TagBuilder("link"); linkTag.MergeAttribute("type", "text/css"); linkTag.MergeAttribute("rel", "stylesheet"); if (mediaType != null) { linkTag.MergeAttribute("media", mediaType); } linkTag.MergeAttribute("href", UrlHelper.GenerateContentUrl(src, helper.ViewContext.HttpContext)); return MvcHtmlString.Create(linkTag.ToString(TagRenderMode.SelfClosing)); }
private static string BuildWidget() { var widget = new TagBuilder("div"); widget.MergeAttribute("class", "g-recaptcha"); widget.MergeAttribute("data-sitekey", ReCaptchaConfiguration.Instance.SiteKey); return widget.ToString(TagRenderMode.Normal); }
internal AccordionPanel(TextWriter writer, string title, string panelId, string parentAccordionId) { if (string.IsNullOrEmpty(title)) { throw new ArgumentNullException("title"); } this.textWriter = writer; this.textWriter.Write(@"<div class=""accordion-group"">"); TagBuilder builder = new TagBuilder("div"); builder.AddCssClass("accordion-heading"); TagBuilder builder2 = new TagBuilder("a"); builder2.Attributes.Add("href", "#" + panelId); builder2.AddCssClass("accordion-toggle"); builder2.InnerHtml = title; builder2.MergeAttribute("data-toggle", "collapse"); builder2.MergeAttribute("data-parent", "#" + parentAccordionId); builder.InnerHtml = builder2.ToString(); this.textWriter.Write(builder.ToString()); builder = new TagBuilder("div"); builder.AddCssClass("accordion-body collapse"); builder.MergeAttribute("id", panelId); this.textWriter.Write(builder.ToString(TagRenderMode.StartTag)); this.textWriter.Write(@"<div class=""accordion-inner"">"); }
public static IHtmlString Render(string virtualPath, string alt = null, string width = null, string height = null, string @class = null, string style = null) { if (Common.IsRenderedTagCached(virtualPath)) return Common.GetCachedRenderedTag(virtualPath); var johnnyPath = Common.BuildJohnnyPath(virtualPath); var tb = new TagBuilder("img"); tb.MergeAttribute("src", johnnyPath); if (!String.IsNullOrWhiteSpace(alt)) tb.MergeAttribute("alt", alt); if (!String.IsNullOrWhiteSpace(width)) tb.MergeAttribute("width", width); if (!String.IsNullOrWhiteSpace(height)) tb.MergeAttribute("height", height); if (!String.IsNullOrWhiteSpace(@class)) tb.MergeAttribute("class", @class); if (!String.IsNullOrWhiteSpace(style)) tb.MergeAttribute("style", style); var renderedTag = MvcHtmlString.Create(tb.ToString()); Common.CacheRenderedTag(virtualPath, renderedTag); return renderedTag; }
protected override void BeforeRenderContentAreaItemStartTag(TagBuilder tagBuilder, ContentAreaItem contentAreaItem) { var highLight = HttpContext.Current.Request[Constants.HighlightQueryStringKey]; if (highLight != null && highLight.Equals(contentAreaItem.GetContent().ContentGuid.ToString())) tagBuilder.AddCssClass(HighlightedCssClass); base.BeforeRenderContentAreaItemStartTag(tagBuilder, contentAreaItem); }
///<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 string ClearDiv() { var myClearDiv = new TagBuilder("div"); myClearDiv.MergeAttribute("class", "clear"); myClearDiv.InnerHtml = " "; return myClearDiv.ToString(); }
public override System.Web.Mvc.MvcHtmlString CreateHtmlElement() { TagBuilder tb = new TagBuilder("input"); tb.Attributes["type"] = "file"; tb.Attributes["name"] = ElementID; return MvcHtmlString.Create(tb.ToString()); }
private static BootstrapAlert BeginAlertHelper(this HtmlHelper html, string alertClassName, string title, string id, string className) { TagBuilder tag = new TagBuilder("div"); tag.AddOrMergeAttribute("class", "alert"); if (!String.IsNullOrEmpty(alertClassName)) tag.AddOrMergeAttribute("class", alertClassName); if (!String.IsNullOrEmpty(className)) tag.AddOrMergeAttribute("class", className); if (!String.IsNullOrEmpty(id)) tag.Attributes.Add("id", id); html.ViewContext.Writer.Write(tag.ToString(TagRenderMode.StartTag)); if (!String.IsNullOrEmpty(title)) { TagBuilder titleTag = new TagBuilder("h4"); titleTag.MergeAttribute("class", "alert-heading"); titleTag.SetInnerText(title); html.ViewContext.Writer.Write(titleTag.ToString(TagRenderMode.Normal)); } BootstrapAlert theAlert = new BootstrapAlert(html.ViewContext); return theAlert; }
/// <summary> /// Loads a script int the view /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="configKey">configuration key value, configured in appsettings</param> /// <returns></returns> /// <exception cref="System.Exception"></exception> public static MvcHtmlString Script(this HtmlHelper htmlHelper, string filePath) { if (UseContentDeliveryNetwork) filePath = filePath.Replace("~", ContentUrlPrefix); if (string.Compare(WorkEnvironment, "Development", StringComparison.CurrentCultureIgnoreCase) == 0) { var filePathWithoutMin = filePath.Replace(".min", string.Empty); if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(filePathWithoutMin))) { filePath = filePathWithoutMin; } } if (string.IsNullOrEmpty(filePath)) { throw new Exception(string.Format("Mvc3.ContentManagement: Resource not found for {0}", filePath)); } else { TagBuilder tagBuilder = new TagBuilder("script"); tagBuilder.MergeAttribute("src", UrlHelper.GenerateContentUrl(filePath, htmlHelper.ViewContext.HttpContext)); tagBuilder.MergeAttribute("type", "text/javascript"); return new MvcHtmlString(tagBuilder.ToString()); } }
public static MvcHtmlString InputHelper(InputTypeHelper inputType,string name, string value, string innerScript,string classAttr, object htmlAttributes) { StringBuilder strBuilder = new StringBuilder(); TagBuilder tagScript = new TagBuilder("script"); tagScript.InnerHtml = "$(document).ready(function () {"; tagScript.InnerHtml += innerScript; tagScript.InnerHtml += "});"; strBuilder.Append(tagScript.ToString()); TagBuilder tagInput = new TagBuilder("input"); if (htmlAttributes != null) tagInput.MergeAttributes<string, object>(((IDictionary<string, object>)new RouteValueDictionary(htmlAttributes))); tagInput.MergeAttribute("type",inputType.ToString()); tagInput.MergeAttribute("name", name); tagInput.MergeAttribute("id", name); tagInput.MergeAttribute("class", classAttr); if(inputType==InputTypeHelper.button) tagInput.MergeAttribute("title", value); else tagInput.MergeAttribute("value", value); strBuilder.Append(tagInput.ToString(TagRenderMode.SelfClosing)); return MvcHtmlString.Create(strBuilder.ToString()); }
public static MvcHtmlString ImageActionLink(this HtmlHelper helper, string imageUrl, string altText, string actionName, string controllerName, object routeValues, object linkHtmlAttributes, object imgHtmlAttributes) { var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(imgHtmlAttributes); var builder = new TagBuilder("img"); builder.MergeAttribute("src", imageUrl); builder.MergeAttribute("alt", altText); foreach (var key in attributes.Keys) { var value = attributes[key]; string valueAsString = null; if (value != null) { valueAsString = value.ToString(); } builder.MergeAttribute(key, valueAsString); } //var link = helper.ActionLink("[placeholder]", actionName, controllerName, routeValues, linkHtmlAttributes); //var text = link.ToHtmlString(); var text = ""; text.Replace("[placeholder]", builder.ToString(TagRenderMode.SelfClosing)); return MvcHtmlString.Create(text); }
public IHtmlContent ContentZone(dynamic Display, dynamic Shape) { var htmlContents = new List<IHtmlContent>(); var shapes = ((IEnumerable<dynamic>)Shape); var tabbed = shapes.GroupBy(x => (string)x.Metadata.Tab); if (tabbed.Count() > 1) { foreach (var tab in tabbed) { var tabName = String.IsNullOrWhiteSpace(tab.Key) ? "Content" : tab.Key; var tabBuilder = new TagBuilder("div"); tabBuilder.Attributes["id"] = "tab-" + tabName.HtmlClassify(); tabBuilder.Attributes["data-tab"] = tabName; foreach (var item in tab) { tabBuilder.InnerHtml.AppendHtml(Display(item)); } htmlContents.Add(tabBuilder); } } else { foreach (var item in tabbed.First()) { htmlContents.Add(Display(item)); } } // TODO: Replace by HtmlContentBuilder when available var combined = new DisplayHelper.Combined(htmlContents); return combined; }
public static TagBuilder StyledHtmlDiv(string aStyle, string aLink) { var myComplaintDiv = new TagBuilder("div"); myComplaintDiv.MergeAttribute("class", aStyle); myComplaintDiv.InnerHtml = aLink; return myComplaintDiv; }
public static MvcHtmlString PageLinks( this HtmlHelper html, PagingInfo info, Func<int, string> url ) { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= info.TotalPages; i++) { TagBuilder tag = null; if (i == info.CurrentPage) { tag = new TagBuilder("span"); tag.AddCssClass("selected"); } else { tag = new TagBuilder("a"); tag.MergeAttribute("href", url(i)); } tag.InnerHtml = i.ToString(CultureInfo.InvariantCulture); sb.Append(tag.ToString()); } return MvcHtmlString.Create(sb.ToString()); }
public static string CheckBoxList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> listInfo, IDictionary<string, object> htmlAttributes) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The argument must have a value", "name"); } if (listInfo == null) { throw new ArgumentNullException("listInfo"); } var sb = new StringBuilder(); foreach (SelectListItem info in listInfo) { var builder = new TagBuilder("input"); if (info.Selected) { builder.MergeAttribute("checked", "checked"); } builder.MergeAttributes(htmlAttributes); builder.MergeAttribute("type", "checkbox"); builder.MergeAttribute("value", info.Value); builder.MergeAttribute("name", name); builder.InnerHtml = info.Text; sb.Append(builder.ToString(TagRenderMode.Normal)); sb.Append("<br />"); } return sb.ToString(); }
/// <summary> /// Function to render the HTML block for the update/cancel buttons for a details edit form /// </summary> /// <param name="helper">Reference to the HTML helper class</param> /// <returns>HTML string for the buttons block</returns> public static HtmlString TestTagBuilder() { // Create the tags we need var div = new TagBuilder("div"); var update = new TagBuilder("a"); var cancel = new TagBuilder("a"); // Center the div tag div.AddCssClass("details-update-button-set"); // Set up the update submit button update.Attributes.Add("id", "save-button"); update.Attributes.Add("tabindex", "0"); update.AddCssClass("snap-button k-button k-button-icontext"); update.SetInnerText("Update"); // Set up the cancel button cancel.Attributes.Add("id", "cancel-button"); cancel.Attributes.Add("tabindex", "0"); cancel.AddCssClass("snap-button k-button k-button-icontext"); cancel.SetInnerText("Cancel"); // Set the HTML for the div and return it div.InnerHtml = update.ToString() + cancel.ToString(); return new HtmlString(div.ToString()); }
/// <summary> /// Get Google Maps Canvas Tag /// </summary> /// <returns></returns> private static string GetGoogleMapCanvas() { var canvasBuilder = new TagBuilder("div"); canvasBuilder.MergeAttribute("id", "map_canvas"); canvasBuilder.MergeAttribute("style", @"height: 500px"); return "\n" + canvasBuilder.ToString(); }
public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, MultiSelectList listInfo, IDictionary<string, object> htmlAttributes) { if (String.IsNullOrEmpty(name)) throw new ArgumentException("The argument must have a value", "name"); if (listInfo == null) throw new ArgumentNullException("listInfo"); if (listInfo.Count() < 1) throw new ArgumentException("The list must contain at least one value", "listInfo"); StringBuilder sb = new StringBuilder(); foreach (SelectListItem info in listInfo) { TagBuilder builder = new TagBuilder("input"); if (info.Selected) builder.MergeAttribute("checked", "checked"); builder.MergeAttributes<string, object>(htmlAttributes); builder.MergeAttribute("type", "checkbox"); builder.MergeAttribute("value", info.Value); builder.MergeAttribute("name", name); builder.InnerHtml = info.Text; sb.Append(builder.ToString(TagRenderMode.Normal)); sb.Append("<br />"); } return MvcHtmlString.Create(sb.ToString()); }
public override void RenderConent(System.Web.UI.HtmlTextWriter writer) { TagBuilder tbTitleUl = new TagBuilder("ul"); tbTitleUl.AddCssClass("tabul"); string divContent = ""; foreach (var item in Collection) { TagBuilder tbTitleLi = new TagBuilder("li"); tbTitleLi.MergeAttribute("style", "cursor:pointer"); tbTitleLi.InnerHtml = item.Title; tbTitleUl.InnerHtml += "\r\n" + tbTitleLi.ToString(); TagBuilder tbContent = new TagBuilder("div"); tbContent.MergeAttribute("style", "display:none"); tbContent.InnerHtml = item.Content; divContent += tbContent.ToString(); } string htmlString = tbTitleUl.ToString() + divContent; writer.Write(htmlString); Tools.RegisterStartupScript(ViewContext, "$('#"+base.Name+"').tabClick().tabHover()"); ////JavaScript 第一種。 c#寫多點 js少點 //JqueryBuilder.Singleton.Selector("selfTab li:nth-child(1)") // .Click((r) => { r.Selector("selfTab div").Hide(); r.Selector("selfTab div:nth-child(2)").Show(); }) // .RenderScript(ViewContext); //JqueryBuilder.Singleton.Selector("selfTab li:nth-child(2)") // .Click((r) => { r.Selector("selfTab div").Hide(); r.Selector("selfTab div:nth-child(3)").Show(); }) // .RenderScript(ViewContext); //JavaScript 第二種 用Options js多點 C#少點 }
internal static void Write(HierarchyNode<ContentItem> hierarchy, ContentItem selectedItem, IContentAdapterProvider adapters, ItemFilter filter, string selectableTypes, string selectableExtensions, bool excludeRoot, string target, TextWriter writer) { N2.Web.Tree.Using(hierarchy) .OpenTo(selectedItem) .Filters(filter) .IdProvider(n => "u" + n.Current.ID, n => "l" + n.Current.ID) .LinkWriter((n, w) => { BuildLink(adapters.ResolveAdapter<NodeAdapter>(n.Current), n.Current, n.Current.Path == selectedItem.Path, target, IsSelectable(n.Current, selectableTypes, selectableExtensions)).WriteTo(w); if (n.Children.Count == 0 && adapters.ResolveAdapter<NodeAdapter>(n.Current).HasChildren(n.Current, filter)) { var ul = new TagBuilder("ul"); ul.AddCssClass("ajax"); w.Write(ul.ToString(TagRenderMode.StartTag)); var li = new TagBuilder("li"); li.InnerHtml = "{url:" + Url.ParseTokenized("{ManagementUrl}/Content/Navigation/LoadTree.ashx") .AppendQuery("target", target) .AppendQuery(SelectionUtility.SelectedQueryKey, HttpUtility.UrlEncode(n.Current.Path)) .AppendQuery("selectableTypes", selectableTypes) .AppendQuery("selectableExtensions", selectableExtensions) + "}"; w.Write(li.ToString()); w.Write(ul.ToString(TagRenderMode.EndTag)); } }) .ExcludeRoot(excludeRoot) .WriteTo(writer); }
public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, IDictionary <string, object> htmlAttributes) { if (htmlHelper == null) { throw new ArgumentNullException("htmlHelper"); } FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation(); if (formContext == null && htmlHelper.ViewData.ModelState.IsValid) { return(null); } string messageSpan; if (!String.IsNullOrEmpty(message)) { TagBuilder spanTag = new TagBuilder("span"); spanTag.SetInnerText(message); messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine; } else { messageSpan = null; } StringBuilder htmlSummary = new StringBuilder(); TagBuilder unorderedList = new TagBuilder("ul"); IEnumerable <ModelState> modelStates = null; if (excludePropertyErrors) { ModelState ms; htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms); if (ms != null) { modelStates = new ModelState[] { ms }; } } else { modelStates = htmlHelper.ViewData.ModelState.Values; } if (modelStates != null) { foreach (ModelState modelState in modelStates) { foreach (ModelError modelError in modelState.Errors) { string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */); if (!String.IsNullOrEmpty(errorText)) { TagBuilder listItem = new TagBuilder("li"); listItem.SetInnerText(errorText); htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal)); } } } } if (htmlSummary.Length == 0) { htmlSummary.AppendLine(_hiddenListItem); } unorderedList.InnerHtml = htmlSummary.ToString(); TagBuilder divBuilder = new TagBuilder("div"); divBuilder.MergeAttributes(htmlAttributes); divBuilder.AddCssClass((htmlHelper.ViewData.ModelState.IsValid) ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName); divBuilder.InnerHtml = messageSpan + unorderedList.ToString(TagRenderMode.Normal); if (formContext != null) { // client val summaries need an ID divBuilder.GenerateId("validationSummary"); formContext.ValidationSummaryId = divBuilder.Attributes["id"]; formContext.ReplaceValidationSummary = !excludePropertyErrors; } return(divBuilder.ToMvcHtmlString(TagRenderMode.Normal)); }
public MvcHtmlString GetHtml(object htmlAttributes = null) { if (this.model == null) { throw new Exception("Cannot render grid. Model is null"); } var wrapperDiv = new TagBuilder("div"); wrapperDiv.MergeAttributes(new RouteValueDictionary(htmlAttributes)); wrapperDiv.AddCssClass("grid"); if (!string.IsNullOrEmpty(this.Title)) { wrapperDiv.InnerHtml += new TagBuilder("h2") { InnerHtml = this.Title } } ; if (this.model.Any()) { // the way the grid is bound depends on the "Count" property. If it has been set, then // the grid will be virtually paged, otherwise it won't be paged at all WebGrid webGrid = null; if (this.Count.HasValue) { Debug.Assert(this.RowsPerPage.HasValue); webGrid = new WebGrid(canPage: true, sortFieldName: "SortBy", sortDirectionFieldName: "SortDirection", pageFieldName: "Page", rowsPerPage: this.RowsPerPage.Value); webGrid.Bind((IEnumerable <dynamic>) this.model, null, false, this.Count.Value); } else { webGrid = new WebGrid(canPage: false); webGrid.Bind((IEnumerable <dynamic>) this.model); } var webGridColumns = new List <WebGridColumn>(); foreach (var field in this.Fields) { PropertyInfo propertyInfo = null; var expressionPropertyValue = ((dynamic)field).Expression; if (expressionPropertyValue != null) { propertyInfo = (PropertyInfo)((MemberExpression)((LambdaExpression)expressionPropertyValue).Body).Member; } else { if (field.Format == null) { throw new Exception("When the format is not specified, the field expression cannot be null"); } } string columnHeader; if (field.Header != null) { columnHeader = field.Header; } else { var displayAttribute = propertyInfo != null ? propertyInfo.GetCustomAttributes(true) .OfType <DisplayAttribute>() .FirstOrDefault() : null; if (displayAttribute != null) { columnHeader = displayAttribute.Name; if (string.IsNullOrEmpty(columnHeader)) { columnHeader = propertyInfo.Name; } } else { columnHeader = propertyInfo != null ? propertyInfo.Name : ""; } } var format = field.Format ?? (x => propertyInfo.GetValue(((WebGridRow)x).Value, null)); var cssClasses = new List <string>(); if (field.WordWrap) { cssClasses.Add("no-wrap-column"); } if (field.CssClass != null) { cssClasses.Add(field.CssClass); } webGridColumns.Add( webGrid.Column( style: string.Join(" ", cssClasses), header: columnHeader, format: format, canSort: field.CanSort)); } wrapperDiv.InnerHtml += new MvcHtmlString(webGrid.GetHtml( columns: webGridColumns, tableStyle: "webgrid", headerStyle: "webgrid-header", footerStyle: "webgrid-footer", alternatingRowStyle: "webgrid-alternating-row", selectedRowStyle: "webgrid-selected-row", rowStyle: "webgrid-row-style").ToString()); } else { var noRecords = new TagBuilder("div"); noRecords.AddCssClass("message-warning"); noRecords.SetInnerText("Não existem registros a serem exibidos"); wrapperDiv.InnerHtml += noRecords; } return(new MvcHtmlString(wrapperDiv.ToString())); } }
public static TagBuilder DropDown(this TagBuilder tagBuilder, Type enumType, string selected = null) { return(tagBuilder.Child(enumType.DropDown(selected))); }
public static IHtmlString ValidationMessage(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, IDictionary <string, object> htmlAttributes) { htmlAttributes = htmlAttributes ?? new RouteValueDictionary(); var validationMessage = ""; string fullHtmlFieldName = htmlAttributes["name"] == null ? modelMetadata.PropertyName : htmlAttributes["name"].ToString(); if (!string.IsNullOrEmpty(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix)) { fullHtmlFieldName = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix + "." + fullHtmlFieldName; } FormContext formContextForClientValidation = htmlHelper.ViewContext.FormContext; //if (htmlHelper.ViewContext.ClientValidationEnabled) //{ // formContextForClientValidation = htmlHelper.ViewContext.FormContext; //} //if (!htmlHelper.ViewData.ModelState.ContainsKey(fullHtmlFieldName) && (formContextForClientValidation == null)) //{ // return null; //} ModelState modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName]; ModelErrorCollection errors = (modelState == null) ? null : modelState.Errors; ModelError error = ((errors == null) || (errors.Count == 0)) ? null : errors[0]; if ((error == null) && (formContextForClientValidation == null)) { return(null); } TagBuilder builder = new TagBuilder("span"); builder.MergeAttributes <string, object>(htmlAttributes); builder.AddCssClass((error != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName); if (!string.IsNullOrEmpty(validationMessage)) { builder.SetInnerText(validationMessage); } else if (error != null) { builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, error, modelState)); } if (formContextForClientValidation != null) { bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage); FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, fullHtmlFieldName); // rules will already have been written to the metadata object fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) { builder.MergeAttribute("data-valmsg-for", fullHtmlFieldName); builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant()); } else { // client validation always requires an ID builder.GenerateId(fullHtmlFieldName + "_validationMessage"); fieldMetadata.ValidationMessageId = builder.Attributes["id"]; } } //if (formContext != null) //{ // bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage); // FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName); // // rules will already have been written to the metadata object // fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified // if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) // { // builder.MergeAttribute("data-valmsg-for", modelName); // builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant()); // } // else // { // // client validation always requires an ID // builder.GenerateId(modelName + "_validationMessage"); // fieldMetadata.ValidationMessageId = builder.Attributes["id"]; // } //} return(new HtmlString(builder.ToString(TagRenderMode.Normal))); }
public static TagBuilder CheckedIf(this TagBuilder tagBuilder, bool condition) { return(tagBuilder.AttrIf(condition, "checked", "checked")); }
public static TagBuilder Name(this TagBuilder tagBuilder, string name) { return(tagBuilder.Attr("name", name)); }
public static TagBuilder IdIfNone(this TagBuilder tagBuilder, string id) { string existing = tagBuilder.Attributes.ContainsKey("id") ? tagBuilder.Attributes["id"] : string.Empty; return(tagBuilder.IdIf(string.IsNullOrEmpty(existing), id)); }
public static TagBuilder Id(this TagBuilder tagBuilder, string id) { return(tagBuilder.Attr("id", id)); }
public static string Id(this TagBuilder tagBuilder) { return(tagBuilder.Attributes["id"]); }
/// <summary> /// Adds a label element as a child using the specified forName and text. /// </summary> /// <param name="tagBuilder"></param> /// <param name="forName"></param> /// <param name="text"></param> /// <returns></returns> public static TagBuilder Label(this TagBuilder tagBuilder, string forName, string text) { return(tagBuilder.Child(new TagBuilder("label").Attr("for", forName).Text(text))); }
/// <summary> /// Adds attribute type="radio" /// </summary> /// <param name="tagBuilder"></param> /// <returns></returns> public static TagBuilder Radio(this TagBuilder tagBuilder) { return(tagBuilder.Attr("type", "radio")); }
/// <summary> /// Adds selected="selected" if the condition is true /// </summary> /// <param name="tagBuilder"></param> /// <param name="condition"></param> /// <returns></returns> public static TagBuilder SelectIf(this TagBuilder tagBuilder, bool condition) { return(tagBuilder.AttrIf(condition, "selected", "selected")); }
/// <summary> /// Adds a style entry /// </summary> /// <param name="tagBuilder"></param> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> public static TagBuilder Style(this TagBuilder tagBuilder, string name, string value) { return(tagBuilder.Css(name, value)); }
/// <summary> /// Appends the specified child to the current TagBuilder /// </summary> /// <param name="tagBuilder"></param> /// <param name="child"></param> /// <returns></returns> public static TagBuilder Child(this TagBuilder tagBuilder, TagBuilder child, TagRenderMode mode = TagRenderMode.Normal) { return(tagBuilder.Child(child.Render())); }
public static TagBuilder Select(this TagBuilder tagBuilder) { return(tagBuilder.Attr("selected", "selected")); }
/// <summary> /// Adds the specified child as the first element in the current TagBuilder if /// the specified condition is true /// </summary> /// <param name="tagBuilder"></param> /// <param name="condition"></param> /// <param name="child"></param> /// <returns></returns> public static TagBuilder FirstChildIf(this TagBuilder tagBuilder, bool condition, TagBuilder child) { if (condition) { return(tagBuilder.FirstChild(child)); } else { return(tagBuilder); } }
/// <summary> /// Wraps the current TagBuilder in the specified tagName and returns /// the parent. /// </summary> /// <param name="tagBuilder"></param> /// <param name="tagName"></param> /// <returns></returns> public static TagBuilder Parent(this TagBuilder tagBuilder, string tagName) { return(new TagBuilder(tagName).Child(tagBuilder)); }
public static TagBuilder ValueIf(this TagBuilder tagBuilder, bool condition, string value) { return(tagBuilder.AttrIf(condition, "value", value)); }
/// <summary> /// Adds the specified child as the first element in the current TagBuilder /// </summary> /// <param name="tagBuilder"></param> /// <param name="child"></param> /// <returns></returns> public static TagBuilder FirstChild(this TagBuilder tagBuilder, TagBuilder child) { return(tagBuilder.FirstChild(child.ToString())); }
/// <summary> /// 配置 /// </summary> protected void Config(TagBuilder builder) { ConfigId(builder); ConfigContent(builder); }
private static HelperResult PagerList( WebGrid webGrid, WebGridPagerModes mode, string firstText, string previousText, string nextText, string lastText, int numericLinksCount, string paginationStyle, bool explicitlyCalled) { int currentPage = webGrid.PageIndex; int totalPages = webGrid.PageCount; int lastPage = totalPages - 1; var ul = new TagBuilder("ul"); ul.AddCssClass(paginationStyle); var li = new List <TagBuilder>(); if (webGrid.TotalRowCount <= webGrid.PageCount) { return(new HelperResult(writer => { writer.Write(string.Empty); })); } if (ModeEnabled(mode, WebGridPagerModes.FirstLast)) { if (String.IsNullOrEmpty(firstText)) { firstText = "First"; } var part = new TagBuilder("li") { InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(0), firstText) }; if (currentPage == 0) { part.MergeAttribute("class", "disabled"); } li.Add(part); } if (ModeEnabled(mode, WebGridPagerModes.NextPrevious)) { if (String.IsNullOrEmpty(previousText)) { previousText = "Prev"; } int page = currentPage == 0 ? 0 : currentPage - 1; var part = new TagBuilder("li") { InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(page), previousText) }; if (currentPage == 0) { part.MergeAttribute("class", "disabled"); } li.Add(part); } if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1)) { int last = currentPage + (numericLinksCount / 2); int first = last - numericLinksCount + 1; if (last > lastPage) { first -= last - lastPage; last = lastPage; } if (first < 0) { last = Math.Min(last + (0 - first), lastPage); first = 0; } for (int i = first; i <= last; i++) { var pageText = (i + 1).ToString(CultureInfo.InvariantCulture); var part = new TagBuilder("li") { InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(i), pageText) }; if (i == currentPage) { part.MergeAttribute("class", "active"); } li.Add(part); } } if (ModeEnabled(mode, WebGridPagerModes.NextPrevious)) { if (String.IsNullOrEmpty(nextText)) { nextText = "Next"; } int page = currentPage == lastPage ? lastPage : currentPage + 1; var part = new TagBuilder("li") { InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(page), nextText) }; if (currentPage == lastPage) { part.MergeAttribute("class", "disabled"); } li.Add(part); } if (ModeEnabled(mode, WebGridPagerModes.FirstLast)) { if (String.IsNullOrEmpty(lastText)) { lastText = "Last"; } var part = new TagBuilder("li") { InnerHtml = GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText) }; if (currentPage == lastPage) { part.MergeAttribute("class", "disabled"); } li.Add(part); } ul.InnerHtml = string.Join("", li); var html = ""; if (explicitlyCalled && webGrid.IsAjaxEnabled) { var span = new TagBuilder("span"); span.MergeAttribute("data-swhgajax", "true"); span.MergeAttribute("data-swhgcontainer", webGrid.AjaxUpdateContainerId); span.MergeAttribute("data-swhgcallback", webGrid.AjaxUpdateCallback); span.InnerHtml = ul.ToString(); html = span.ToString(); } else { html = ul.ToString(); } return(new HelperResult(writer => { writer.Write(html); })); }
public static TagBuilder DropDown(this TagBuilder tagBuilder, Dictionary <string, string> options, string selected = null) { return(tagBuilder.Child(options.DropDown(selected))); }
public static MvcHtmlString ExtCheckBoxListFor <TModel, TValue>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, IEnumerable <TValue> > > expression, IEnumerable <SelectListItem> values, IEnumerable <TValue> selectedIds, int columnNumber = 1, object htmlAttributes = null) { if (columnNumber <= 1) { return(htmlHelper.ExtCheckBoxListSingleColumnFor(expression, values, selectedIds, htmlAttributes)); } var isDisabled = false; var html = htmlAttributes == null ? new RouteValueDictionary() : new RouteValueDictionary(htmlAttributes); if (html["disabled"] != null && html["disabled"].ToString() == "disabled") { isDisabled = true; } var variableName = ExpressionHelper.GetExpressionText(expression); var itemName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(variableName); var selectedValues = selectedIds.Select(x => x.ToString()).ToList(); var selectListItems = values.ToList(); var rowNumber = selectListItems.Count / columnNumber + 1; var tableBuilder = new TagBuilder("table"); for (var rowIndex = 0; rowIndex < rowNumber; rowIndex++) { var trBuilder = new TagBuilder("tr"); for (var columnIndex = 0; columnIndex < columnNumber; columnIndex++) { var itemIndex = rowIndex * columnNumber + columnIndex; if (itemIndex >= selectListItems.Count) { break; } var itemId = itemName + CustomControlHelper.GetControlCount(itemName); var inputBuilder = new TagBuilder("input"); inputBuilder.MergeAttribute("id", itemId); inputBuilder.MergeAttribute("name", itemName); inputBuilder.MergeAttribute("type", "checkbox"); inputBuilder.MergeAttribute("value", selectListItems[itemIndex].Value); if (selectedValues.Contains(selectListItems[itemIndex].Value)) { inputBuilder.MergeAttribute("checked", "checked"); } if (isDisabled) { inputBuilder.MergeAttribute("disabled", "disabled"); } var labelInner = inputBuilder + selectListItems[itemIndex].Text; var labelBuilder = new TagBuilder("label"); labelBuilder.MergeAttribute("for", itemId); labelBuilder.InnerHtml = labelInner; var divBuilder = new TagBuilder("div"); //divBuilder.AddCssClass("checkbox"); if (isDisabled) { divBuilder.AddCssClass("disabled"); } divBuilder.InnerHtml = labelBuilder.ToString(); var tdBuilder = new TagBuilder("td") { InnerHtml = divBuilder.ToString() }; trBuilder.InnerHtml += tdBuilder.ToString(); } tableBuilder.InnerHtml += trBuilder.ToString(); } return(CustomControlHelper.GenerateWithValidationMessage(htmlHelper, tableBuilder.ToString(), expression)); }
public static TagBuilder Type(this TagBuilder tagBuilder, string value) { return(tagBuilder.Attr("type", value)); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (!isVisible) { output.SuppressOutput(); return; } #region << Init >> var initSuccess = InitField(context, output); if (!initSuccess) { return; } #region << Init Prepend and Append >> var content = await output.GetChildContentAsync(); var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(content.GetContent()); var prependTaghelper = htmlDoc.DocumentNode.Descendants("wv-field-prepend"); var appendTagHelper = htmlDoc.DocumentNode.Descendants("wv-field-append"); foreach (var node in prependTaghelper) { PrependHtml.Add(node.InnerHtml.ToString()); } foreach (var node in appendTagHelper) { AppendHtml.Add(node.InnerHtml.ToString()); } #endregion #endregion #region << Render >> if (Mode == WvFieldRenderMode.Form) { var inputReadOnlyValue = ""; var inputEditValue = ""; if (Value != null) { inputReadOnlyValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).WvConvertToTZDate(TimezoneName).Value.ToString("dd MMM yyyy", Culture); inputEditValue = (Value ?? DateTime.Now).ToString("yyyy-MM-ddT00:00:00.000"); } var inputGroupEl = new TagBuilder("div"); inputGroupEl.AddCssClass("input-group"); //Prepend if (PrependHtml.Count > 0) { var prependEl = new TagBuilder("span"); prependEl.AddCssClass($"input-group-prepend {(ValidationErrors.Count > 0 ? "is-invalid" : "")}"); foreach (var htmlString in PrependHtml) { prependEl.InnerHtml.AppendHtml(htmlString); } inputGroupEl.InnerHtml.AppendHtml(prependEl); } //Control var inputEl = new TagBuilder("input"); var inputElCssClassList = new List <string>(); inputElCssClassList.Add("form-control erp-date"); inputEl.Attributes.Add("type", "text"); inputEl.Attributes.Add("id", $"input-{FieldId}"); inputEl.Attributes.Add("name", Name); if (Access == WvFieldAccess.Full || Access == WvFieldAccess.FullAndCreate) { if (Required) { inputEl.Attributes.Add("required", null); } if (!String.IsNullOrWhiteSpace(Placeholder)) { inputEl.Attributes.Add("placeholder", Placeholder); } inputEl.Attributes.Add("value", inputEditValue); } else if (Access == WvFieldAccess.ReadOnly) { inputEl.Attributes.Add("value", inputReadOnlyValue); inputEl.Attributes.Add("readonly", null); } if (ValidationErrors.Count > 0) { inputElCssClassList.Add("is-invalid"); } inputEl.Attributes.Add("class", String.Join(' ', inputElCssClassList)); inputGroupEl.InnerHtml.AppendHtml(inputEl); //Append if (AppendHtml.Count > 0) { var appendEl = new TagBuilder("span"); appendEl.AddCssClass($"input-group-append {(ValidationErrors.Count > 0 ? "is-invalid" : "")}"); foreach (var htmlString in AppendHtml) { appendEl.InnerHtml.AppendHtml(htmlString); } inputGroupEl.InnerHtml.AppendHtml(appendEl); } output.Content.AppendHtml(inputGroupEl); if (Access == WvFieldAccess.Full || Access == WvFieldAccess.FullAndCreate) { var jsCompressor = new JavaScriptCompressor(); #region << Init Libraries >> var wvLibraryInitialized = false; var libraryItemsKey = "WebVella-" + "flatpickr"; if (ViewContext.HttpContext.Items.ContainsKey(libraryItemsKey)) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[libraryItemsKey]; wvLibraryInitialized = tagHelperContext.Initialized; } if (!wvLibraryInitialized) { var libCssEl = new TagBuilder("link"); libCssEl.Attributes.Add("href", "/_content/WebVella.TagHelpers/lib/flatpickr/flatpickr.min.css"); libCssEl.Attributes.Add("type", "text/css"); libCssEl.Attributes.Add("rel", "stylesheet"); output.PostContent.AppendHtml(libCssEl); output.PostContent.AppendHtml("\r\n\t"); var libJsEl = new TagBuilder("script"); libJsEl.Attributes.Add("type", "text/javascript"); libJsEl.Attributes.Add("src", "/_content/WebVella.TagHelpers/lib/flatpickr/flatpickr.min.js"); output.PostContent.AppendHtml(libJsEl); output.PostContent.AppendHtml("\r\n\t"); ViewContext.HttpContext.Items[libraryItemsKey] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Init Scripts >> var tagHelperInitialized = false; if (ViewContext.HttpContext.Items.ContainsKey(typeof(WvFieldDate) + "-form")) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-form"]; tagHelperInitialized = tagHelperContext.Initialized; } if (!tagHelperInitialized) { var scriptContent = WvHelpers.GetEmbeddedTextResource("form.js", "WebVella.TagHelpers.TagHelpers.WvFieldDate", "WebVella.TagHelpers"); var scriptEl = new TagBuilder("script"); scriptEl.Attributes.Add("type", "text/javascript"); scriptEl.InnerHtml.AppendHtml(jsCompressor.Compress(scriptContent)); output.PostContent.AppendHtml(scriptEl); ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-form"] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Add Inline Init Script for this instance >> var initScript = new TagBuilder("script"); initScript.Attributes.Add("type", "text/javascript"); var scriptTemplate = @" $(function(){ InitFlatPickrDate(""{{FieldId}}"",{{ConfigJson}}); });" ; scriptTemplate = scriptTemplate.Replace("{{FieldId}}", (FieldId != null ? FieldId.Value.ToString() : "")); var fieldConfig = new WvFieldDateConfig() { IsRequired = Required }; scriptTemplate = scriptTemplate.Replace("{{ConfigJson}}", JsonConvert.SerializeObject(fieldConfig)); initScript.InnerHtml.AppendHtml(jsCompressor.Compress(scriptTemplate)); output.PostContent.AppendHtml(initScript); #endregion } } else if (Mode == WvFieldRenderMode.Display) { if (Value != null) { var inputReadOnlyValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).WvConvertToTZDate(TimezoneName).Value.ToString("dd MMM yyyy", Culture); var divEl = new TagBuilder("div"); divEl.Attributes.Add("id", $"input-{FieldId}"); divEl.AddCssClass("form-control-plaintext erp-date"); divEl.InnerHtml.Append(inputReadOnlyValue); output.Content.AppendHtml(divEl); } else { output.Content.AppendHtml(EmptyValEl); } } else if (Mode == WvFieldRenderMode.Simple) { if (Value != null) { output.SuppressOutput(); var inputReadOnlyValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).WvConvertToTZDate(TimezoneName).Value.ToString("dd MMM yyyy", Culture); output.Content.AppendHtml(inputReadOnlyValue); } else { output.SuppressOutput(); output.Content.AppendHtml(""); } return; } else if (Mode == WvFieldRenderMode.InlineEdit) { if (Access == WvFieldAccess.Full || Access == WvFieldAccess.FullAndCreate) { var editInpuValue = ""; var readOnlyInputValue = ""; if (Value != null) { readOnlyInputValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).WvConvertToTZDate(TimezoneName).Value.ToString("dd MMM yyyy", Culture); editInpuValue = (Value ?? DateTime.Now).ToString("yyyy-MM-ddT00:00:00.000"); } #region << View Wrapper >> { var viewWrapperEl = new TagBuilder("div"); viewWrapperEl.AddCssClass("input-group view-wrapper"); viewWrapperEl.Attributes.Add("title", "double click to edit"); viewWrapperEl.Attributes.Add("id", $"view-{FieldId}"); //Prepend if (PrependHtml.Count > 0) { var viewInputPrepend = new TagBuilder("span"); viewInputPrepend.AddCssClass("input-group-prepend"); foreach (var htmlString in PrependHtml) { viewInputPrepend.InnerHtml.AppendHtml(htmlString); } viewWrapperEl.InnerHtml.AppendHtml(viewInputPrepend); } //Control var viewFormControlEl = new TagBuilder("div"); viewFormControlEl.AddCssClass("form-control erp-date"); viewFormControlEl.InnerHtml.Append(readOnlyInputValue); viewWrapperEl.InnerHtml.AppendHtml(viewFormControlEl); //Append var viewInputActionEl = new TagBuilder("span"); viewInputActionEl.AddCssClass("input-group-append action"); foreach (var htmlString in AppendHtml) { viewInputActionEl.InnerHtml.AppendHtml(htmlString); } viewInputActionEl.InnerHtml.AppendHtml("<button type=\"button\" class='btn btn-white' title='edit'><i class='fa fa-fw fa-pencil-alt'></i></button>"); viewWrapperEl.InnerHtml.AppendHtml(viewInputActionEl); output.Content.AppendHtml(viewWrapperEl); } #endregion #region << Edit Wrapper>> { var editWrapperEl = new TagBuilder("div"); editWrapperEl.Attributes.Add("id", $"edit-{FieldId}"); editWrapperEl.Attributes.Add("style", $"display:none;"); editWrapperEl.Attributes.Add("data-default-date", editInpuValue); //There is a problem with double initializing flatpickr which this solves editWrapperEl.AddCssClass("edit-wrapper"); var editInputGroupEl = new TagBuilder("div"); editInputGroupEl.AddCssClass("input-group"); //Prepend if (PrependHtml.Count > 0) { var editInputPrepend = new TagBuilder("span"); editInputPrepend.AddCssClass("input-group-prepend"); foreach (var htmlString in PrependHtml) { editInputPrepend.InnerHtml.AppendHtml(htmlString); } editInputGroupEl.InnerHtml.AppendHtml(editInputPrepend); } //Control var editInputEl = new TagBuilder("input"); editInputEl.AddCssClass("form-control erp-date"); editInputEl.Attributes.Add("type", "text"); if (Required) { editInputEl.Attributes.Add("required", null); } if (!String.IsNullOrWhiteSpace(Placeholder)) { editInputEl.Attributes.Add("placeholder", Placeholder); } editInputEl.Attributes.Add("value", editInpuValue); editInputGroupEl.InnerHtml.AppendHtml(editInputEl); //Append var editInputGroupAppendEl = new TagBuilder("span"); editInputGroupAppendEl.AddCssClass("input-group-append"); foreach (var htmlString in AppendHtml) { editInputGroupAppendEl.InnerHtml.AppendHtml(htmlString); } editInputGroupAppendEl.InnerHtml.AppendHtml("<button type=\"button\" class='btn btn-white save' title='save'><i class='fa fa-fw fa-check go-green'></i></button>"); editInputGroupAppendEl.InnerHtml.AppendHtml("<button type=\"button\" class='btn btn-white cancel' title='cancel'><i class='fa fa-fw fa-times go-gray'></i></button>"); editInputGroupEl.InnerHtml.AppendHtml(editInputGroupAppendEl); editWrapperEl.InnerHtml.AppendHtml(editInputGroupEl); output.Content.AppendHtml(editWrapperEl); } #endregion var jsCompressor = new JavaScriptCompressor(); #region << Init Libraries >> var wvLibraryInitialized = false; var libraryItemsKey = "WebVella-" + "flatpickr"; if (ViewContext.HttpContext.Items.ContainsKey(libraryItemsKey)) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[libraryItemsKey]; wvLibraryInitialized = tagHelperContext.Initialized; } if (!wvLibraryInitialized) { var libCssEl = new TagBuilder("link"); libCssEl.Attributes.Add("href", "/_content/WebVella.TagHelpers/lib/flatpickr/flatpickr.min.css"); libCssEl.Attributes.Add("type", "text/css"); libCssEl.Attributes.Add("rel", "stylesheet"); output.PostContent.AppendHtml(libCssEl); output.PostContent.AppendHtml("\r\n\t"); var libJsEl = new TagBuilder("script"); libJsEl.Attributes.Add("type", "text/javascript"); libJsEl.Attributes.Add("src", "/_content/WebVella.TagHelpers/lib/flatpickr/flatpickr.min.js"); output.PostContent.AppendHtml(libJsEl); output.PostContent.AppendHtml("\r\n\t"); ViewContext.HttpContext.Items[libraryItemsKey] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Init Scripts >> var tagHelperInitialized = false; if (ViewContext.HttpContext.Items.ContainsKey(typeof(WvFieldDate) + "-inline-edit")) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-inline-edit"]; tagHelperInitialized = tagHelperContext.Initialized; } if (!tagHelperInitialized) { var scriptContent = WvHelpers.GetEmbeddedTextResource("inline-edit.js", "WebVella.TagHelpers.TagHelpers.WvFieldDate", "WebVella.TagHelpers"); var scriptEl = new TagBuilder("script"); scriptEl.Attributes.Add("type", "text/javascript"); scriptEl.InnerHtml.AppendHtml(jsCompressor.Compress(scriptContent)); output.PostContent.AppendHtml(scriptEl); ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-inline-edit"] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Add Inline Init Script for this instance >> var initScript = new TagBuilder("script"); initScript.Attributes.Add("type", "text/javascript"); var scriptTemplate = @" $(function(){ DateInlineEditInit(""{{FieldId}}"",""{{Name}}"",{{ConfigJson}}); });" ; scriptTemplate = scriptTemplate.Replace("{{FieldId}}", (FieldId != null ? FieldId.Value.ToString() : "")); scriptTemplate = scriptTemplate.Replace("{{Name}}", Name); var fieldConfig = new WvFieldDateConfig() { ApiUrl = ApiUrl, CanAddValues = Access == WvFieldAccess.FullAndCreate ? true : false, IsRequired = Required }; scriptTemplate = scriptTemplate.Replace("{{ConfigJson}}", JsonConvert.SerializeObject(fieldConfig)); initScript.InnerHtml.AppendHtml(jsCompressor.Compress(scriptTemplate)); output.PostContent.AppendHtml(initScript); #endregion } else if (Access == WvFieldAccess.ReadOnly) { var readOnlyInputValue = ""; if (Value != null) { readOnlyInputValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).WvConvertToTZDate(TimezoneName).Value.ToString("dd MMM yyyy", Culture); } var divEl = new TagBuilder("div"); divEl.AddCssClass("input-group"); //Prepend if (PrependHtml.Count > 0) { var viewInputPrepend = new TagBuilder("span"); viewInputPrepend.AddCssClass("input-group-prepend"); foreach (var htmlString in PrependHtml) { viewInputPrepend.InnerHtml.AppendHtml(htmlString); } divEl.InnerHtml.AppendHtml(viewInputPrepend); } //Control var inputEl = new TagBuilder("input"); inputEl.AddCssClass("form-control erp-date"); inputEl.Attributes.Add("type", "text"); inputEl.Attributes.Add("value", readOnlyInputValue); inputEl.Attributes.Add("readonly", null); divEl.InnerHtml.AppendHtml(inputEl); //Append var appendActionSpan = new TagBuilder("span"); appendActionSpan.AddCssClass("input-group-append action"); foreach (var htmlString in AppendHtml) { appendActionSpan.InnerHtml.AppendHtml(htmlString); } appendActionSpan.InnerHtml.AppendHtml("<button type=\"button\" disabled class='btn btn-white' title='locked'><i class='fa fa-fw fa-lock'></i></button>"); divEl.InnerHtml.AppendHtml(appendActionSpan); output.Content.AppendHtml(divEl); } } #endregion //Finally if (SubInputEl != null) { output.PostContent.AppendHtml(SubInputEl); } return; }
private static MvcHtmlString Input5Helper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary <string, object> htmlAttributes) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new NullReferenceException("name"); } TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(inputType)); tagBuilder.MergeAttribute("name", fullName, true); tagBuilder.MergeAttribute("DTA", "Was here"); string valueParameter = htmlHelper.FormatValue(value, format); bool usedModelState = false; switch (inputType) { case InputType.CheckBox: bool?modelStateWasChecked = GetModelStateValue(htmlHelper, fullName, typeof(bool)) as bool?; if (modelStateWasChecked.HasValue) { isChecked = modelStateWasChecked.Value; usedModelState = true; } goto case InputType.Radio; case InputType.Radio: if (!usedModelState) { string modelStateValue = GetModelStateValue(htmlHelper, fullName, typeof(string)) as string; if (modelStateValue != null) { isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal); usedModelState = true; } } if (!usedModelState && useViewData) { isChecked = EvalBoolean(htmlHelper, fullName); } if (isChecked) { tagBuilder.MergeAttribute("checked", "checked"); } tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue); break; case InputType.Password: if (value != null) { tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue); } break; default: string attemptedValue = (string)GetModelStateValue(htmlHelper, fullName, typeof(string)); tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? EvalString(htmlHelper, fullName, format) : valueParameter), isExplicitValue); break; } if (setId) { tagBuilder.GenerateId(fullName); } // If there are any errors for a named field, we add the css attribute. ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata)); //Build Html5 attributes //<input data-rel="tooltip" type="text" id="form-field-6" placeholder="Tooltip on hover" title="" data-placement="bottom" data-original-title="Hello Tooltip!"> if (metadata != null) { if (!string.IsNullOrEmpty(metadata.Watermark)) { tagBuilder.Attributes.Add("placeholder", metadata.Watermark); } if (!string.IsNullOrEmpty(metadata.Description)) { tagBuilder.Attributes.Add("data-rel", "tooltip"); tagBuilder.Attributes.Add("data-original-title", metadata.Description); tagBuilder.Attributes.Add("title", null); } } if (inputType == InputType.CheckBox) { // Render an additional <input type="hidden".../> for checkboxes. This // addresses scenarios where unchecked checkboxes are not sent in the request. // Sending a hidden input makes it possible to know that the checkbox was present // on the page when the request was submitted. StringBuilder inputItemBuilder = new StringBuilder(); inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing)); TagBuilder hiddenInput = new TagBuilder("input"); hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden)); hiddenInput.MergeAttribute("name", fullName); hiddenInput.MergeAttribute("value", "false"); inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing)); return(MvcHtmlString.Create(inputItemBuilder.ToString())); } return(MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal))); }
public async Task ProcessAsync_CallsGenerateTextBox_WithExpectedParameters( string dataTypeName, string inputTypeName, string model) { // Arrange var contextAttributes = new Dictionary <string, object> { { "class", "form-control" }, }; if (!string.IsNullOrEmpty(inputTypeName)) { contextAttributes["type"] = inputTypeName; // Support restoration of type attribute, if any. } var expectedAttributes = new Dictionary <string, string> { { "class", "form-control text-control" }, { "type", inputTypeName ?? "text" }, // Generator restores type attribute; adds "text" if none. }; var expectedPreContent = "original pre-content"; var expectedContent = "original content"; var expectedPostContent = "original post-content"; var expectedTagName = "not-input"; var context = new TagHelperContext(allAttributes: contextAttributes, uniqueId: "test", getChildContentAsync: () => Task.FromResult("Something")); var originalAttributes = new Dictionary <string, string> { { "class", "form-control" }, }; var output = new TagHelperOutput(expectedTagName, originalAttributes) { PreContent = expectedPreContent, Content = expectedContent, PostContent = expectedPostContent, SelfClosing = false, }; var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var tagHelper = GetTagHelper(htmlGenerator.Object, model, nameof(Model.Text)); tagHelper.For.Metadata.DataTypeName = dataTypeName; tagHelper.InputTypeName = inputTypeName; var tagBuilder = new TagBuilder("input") { Attributes = { { "class", "text-control" }, }, }; htmlGenerator .Setup(mock => mock.GenerateTextBox( tagHelper.ViewContext, tagHelper.For.Metadata, tagHelper.For.Name, model, // value null, // format null)) // htmlAttributes .Returns(tagBuilder) .Verifiable(); // Act await tagHelper.ProcessAsync(context, output); // Assert htmlGenerator.Verify(); Assert.Equal(expectedAttributes, output.Attributes); Assert.Equal(expectedPreContent, output.PreContent); Assert.Equal(expectedContent, output.Content); Assert.Equal(expectedPostContent, output.PostContent); Assert.True(output.SelfClosing); Assert.Equal(expectedTagName, output.TagName); }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (!isVisible) { output.SuppressOutput(); return(Task.CompletedTask); } #region << Init >> var initSuccess = InitField(context, output); if (!initSuccess) { return(Task.CompletedTask); } #endregion #region << Render >> if (Value == null) { Value = ""; } //Apply Value string if (!String.IsNullOrWhiteSpace(Template)) { Value = String.Format(Template, (Value ?? "").ToString()); } else { Value = (Value ?? "").ToString(); } if (Mode == FieldRenderMode.Form || Mode == FieldRenderMode.InlineEdit) { var inputEl = new TagBuilder("input"); var inputElCssClassList = new List <string>(); inputElCssClassList.Add("form-control erp-autonumber"); inputEl.Attributes.Add("type", "text"); inputEl.Attributes.Add("value", Value); inputEl.Attributes.Add("id", $"input-{FieldId}"); inputEl.Attributes.Add("name", Name); if (Required) { inputEl.Attributes.Add("required", null); } if (!String.IsNullOrWhiteSpace(Placeholder)) { inputEl.Attributes.Add("placeholder", Placeholder); } inputEl.Attributes.Add("readonly", null); if (ValidationErrors.Count > 0) { inputElCssClassList.Add("is-invalid"); } inputEl.Attributes.Add("class", String.Join(' ', inputElCssClassList)); output.Content.AppendHtml(inputEl); } else if (Mode == FieldRenderMode.Display) { var divEl = new TagBuilder("div"); divEl.Attributes.Add("id", $"input-{FieldId}"); divEl.AddCssClass("form-control-plaintext erp-autonumber"); divEl.InnerHtml.Append(Value); output.Content.AppendHtml(divEl); } else if (Mode == FieldRenderMode.Simple) { output.SuppressOutput(); output.Content.AppendHtml(Value); return(Task.CompletedTask); } #endregion //Finally if (SubInputEl != null) { output.PostContent.AppendHtml(SubInputEl); } return(Task.CompletedTask); }
public async Task ProcessAsync_CallsGenerateCheckBox_WithExpectedParameters() { // Arrange var originalContent = "original content"; var originalTagName = "not-input"; var expectedPreContent = "original pre-content"; var expectedContent = originalContent + "<input class=\"form-control\" /><hidden />"; var expectedPostContent = "original post-content"; var context = new TagHelperContext(allAttributes: new Dictionary <string, object>(), uniqueId: "test", getChildContentAsync: () => Task.FromResult("Something")); var originalAttributes = new Dictionary <string, string> { { "class", "form-control" }, }; var output = new TagHelperOutput(originalTagName, originalAttributes) { PreContent = expectedPreContent, Content = originalContent, PostContent = expectedPostContent, SelfClosing = true, }; var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var tagHelper = GetTagHelper(htmlGenerator.Object, model: false, propertyName: nameof(Model.IsACar)); var tagBuilder = new TagBuilder("input") { Attributes = { { "class", "form-control" }, }, }; htmlGenerator .Setup(mock => mock.GenerateCheckBox( tagHelper.ViewContext, tagHelper.For.Metadata, tagHelper.For.Name, null, // isChecked It.IsAny <object>())) // htmlAttributes .Returns(tagBuilder) .Verifiable(); htmlGenerator .Setup(mock => mock.GenerateHiddenForCheckbox( tagHelper.ViewContext, tagHelper.For.Metadata, tagHelper.For.Name)) .Returns(new TagBuilder("hidden")) .Verifiable(); // Act await tagHelper.ProcessAsync(context, output); // Assert htmlGenerator.Verify(); Assert.Empty(output.Attributes); // Moved to Content and cleared Assert.Equal(expectedPreContent, output.PreContent); Assert.Equal(expectedContent, output.Content); Assert.Equal(expectedPostContent, output.PostContent); Assert.False(output.SelfClosing); Assert.Null(output.TagName); // Cleared }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { #region << Init >> var initSuccess = InitField(context, output); if (!initSuccess) { return(Task.CompletedTask); } #endregion #region << Render >> if (Mode == FieldRenderMode.Form) { var wrapperEl = new TagBuilder("div"); wrapperEl.AddCssClass("form-control-plaintext erp-color"); var inputEl = new TagBuilder("input"); var inputElCssClassList = new List <string>(); inputElCssClassList.Add("d-none"); inputEl.Attributes.Add("type", "text"); inputEl.Attributes.Add("value", (Value ?? "").ToString()); inputEl.Attributes.Add("id", $"input-{FieldId}"); inputEl.Attributes.Add("name", Name); if (Access == FieldAccess.Full || Access == FieldAccess.FullAndCreate) { } else if (Access == FieldAccess.ReadOnly) { inputEl.Attributes.Add("readonly", null); } if (ValidationErrors.Count > 0) { inputElCssClassList.Add("is-invalid"); } inputEl.Attributes.Add("class", String.Join(' ', inputElCssClassList)); wrapperEl.InnerHtml.AppendHtml(inputEl); output.Content.AppendHtml(wrapperEl); var jsCompressor = new JavaScriptCompressor(); #region << Init Scripts >> var tagHelperInitialized = false; var fileName = "form.js"; if (ViewContext.HttpContext.Items.ContainsKey(typeof(WvFieldColor) + fileName)) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[typeof(WvFieldColor) + fileName]; tagHelperInitialized = tagHelperContext.Initialized; } if (!tagHelperInitialized) { var scriptContent = FileService.GetEmbeddedTextResource(fileName, "WebVella.Erp.Web.TagHelpers.WvFieldColor"); var scriptEl = new TagBuilder("script"); scriptEl.Attributes.Add("type", "text/javascript"); scriptEl.InnerHtml.AppendHtml(jsCompressor.Compress(scriptContent)); output.PostContent.AppendHtml(scriptEl); ViewContext.HttpContext.Items[typeof(WvFieldColor) + fileName] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Add Inline Init Script for this instance >> var initScript = new TagBuilder("script"); initScript.Attributes.Add("type", "text/javascript"); var scriptTemplate = @" $(function(){ ColorFormInit(""{{FieldId}}""); });" ; scriptTemplate = scriptTemplate.Replace("{{FieldId}}", (FieldId ?? null).ToString()); initScript.InnerHtml.AppendHtml(jsCompressor.Compress(scriptTemplate)); output.PostContent.AppendHtml(initScript); #endregion } else if (Mode == FieldRenderMode.Display) { if (!String.IsNullOrWhiteSpace(Value)) { var divEl = new TagBuilder("div"); divEl.Attributes.Add("id", $"input-{FieldId}"); divEl.AddCssClass("form-control-plaintext erp-color"); var colorDiv = new TagBuilder("div"); colorDiv.AddCssClass("color-box"); colorDiv.Attributes.Add("style", $"background-color:{(Value ?? "").ToString()}"); divEl.InnerHtml.AppendHtml(colorDiv); divEl.InnerHtml.AppendHtml((Value ?? "").ToString()); output.Content.AppendHtml(divEl); } else { output.Content.AppendHtml(EmptyValEl); } } else if (Mode == FieldRenderMode.Simple) { output.SuppressOutput(); output.Content.AppendHtml((Value ?? "").ToString()); return(Task.CompletedTask); } else if (Mode == FieldRenderMode.InlineEdit) { if (Access == FieldAccess.Full || Access == FieldAccess.FullAndCreate) { #region << View Wrapper >> { var viewWrapperEl = new TagBuilder("div"); viewWrapperEl.AddCssClass("input-group view-wrapper"); viewWrapperEl.Attributes.Add("title", "double click to edit"); viewWrapperEl.Attributes.Add("id", $"view-{FieldId}"); var viewInputPrepend = new TagBuilder("span"); viewInputPrepend.AddCssClass("input-group-prepend"); var viewInputPrependText = new TagBuilder("span"); viewInputPrependText.AddCssClass("input-group-text"); viewInputPrependText.Attributes.Add("style", $"background-color:{(Value ?? "").ToString()}; width: 31px;"); viewInputPrependText.InnerHtml.AppendHtml(" "); viewInputPrepend.InnerHtml.AppendHtml(viewInputPrependText); viewWrapperEl.InnerHtml.AppendHtml(viewInputPrepend); var viewFormControlEl = new TagBuilder("div"); viewFormControlEl.AddCssClass("form-control erp-color"); viewFormControlEl.InnerHtml.Append((Value ?? "").ToString()); viewWrapperEl.InnerHtml.AppendHtml(viewFormControlEl); var viewInputActionEl = new TagBuilder("span"); viewInputActionEl.AddCssClass("input-group-append action"); viewInputActionEl.Attributes.Add("title", "edit"); var viewInputActionLinkEl = new TagBuilder("button"); viewInputActionLinkEl.Attributes.Add("type", "button"); viewInputActionLinkEl.AddCssClass("btn btn-white"); var viewInputActionIconEl = new TagBuilder("span"); viewInputActionIconEl.AddCssClass("fa fa-fw fa-pencil-alt"); viewInputActionLinkEl.InnerHtml.AppendHtml(viewInputActionIconEl); viewInputActionEl.InnerHtml.AppendHtml(viewInputActionLinkEl); viewWrapperEl.InnerHtml.AppendHtml(viewInputActionEl); output.Content.AppendHtml(viewWrapperEl); } #endregion #region << Edit Wrapper>> { var editWrapperEl = new TagBuilder("div"); editWrapperEl.Attributes.Add("id", $"edit-{FieldId}"); editWrapperEl.Attributes.Add("style", $"display:none;"); editWrapperEl.AddCssClass("edit-wrapper"); var editInputGroupEl = new TagBuilder("div"); editInputGroupEl.AddCssClass("input-group"); var editInputEl = new TagBuilder("input"); editInputEl.AddCssClass("form-control erp-color"); editInputEl.Attributes.Add("type", "color"); editInputEl.Attributes.Add("value", (Value ?? "").ToString()); editInputGroupEl.InnerHtml.AppendHtml(editInputEl); var editInputGroupAppendEl = new TagBuilder("span"); editInputGroupAppendEl.AddCssClass("input-group-append"); var editSaveBtnEl = new TagBuilder("button"); editSaveBtnEl.Attributes.Add("type", "button"); editSaveBtnEl.AddCssClass("btn btn-white save"); editSaveBtnEl.Attributes.Add("title", "save"); var editSaveIconEl = new TagBuilder("span"); editSaveIconEl.AddCssClass("fa fa-fw fa-check go-green"); editSaveBtnEl.InnerHtml.AppendHtml(editSaveIconEl); editInputGroupAppendEl.InnerHtml.AppendHtml(editSaveBtnEl); var editCancelBtnEl = new TagBuilder("button"); editCancelBtnEl.Attributes.Add("type", "button"); editCancelBtnEl.AddCssClass("btn btn-white cancel"); editCancelBtnEl.Attributes.Add("title", "cancel"); var editCancelIconEl = new TagBuilder("span"); editCancelIconEl.AddCssClass("fa fa-fw fa-times go-gray"); editCancelBtnEl.InnerHtml.AppendHtml(editCancelIconEl); editInputGroupAppendEl.InnerHtml.AppendHtml(editCancelBtnEl); editInputGroupEl.InnerHtml.AppendHtml(editInputGroupAppendEl); editWrapperEl.InnerHtml.AppendHtml(editInputGroupEl); output.Content.AppendHtml(editWrapperEl); } #endregion var jsCompressor = new JavaScriptCompressor(); #region << Init Scripts >> var tagHelperInitialized = false; if (ViewContext.HttpContext.Items.ContainsKey(typeof(WvFieldColor) + "-inline-edit")) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[typeof(WvFieldColor) + "-inline-edit"]; tagHelperInitialized = tagHelperContext.Initialized; } if (!tagHelperInitialized) { var scriptContent = FileService.GetEmbeddedTextResource("inline-edit.js", "WebVella.Erp.Web.TagHelpers.WvFieldColor"); var scriptEl = new TagBuilder("script"); scriptEl.Attributes.Add("type", "text/javascript"); scriptEl.InnerHtml.AppendHtml(jsCompressor.Compress(scriptContent)); output.PostContent.AppendHtml(scriptEl); ViewContext.HttpContext.Items[typeof(WvFieldColor) + "-inline-edit"] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Add Inline Init Script for this instance >> var initScript = new TagBuilder("script"); initScript.Attributes.Add("type", "text/javascript"); var scriptTemplate = @" $(function(){ ColorInlineEditInit(""{{FieldId}}"",""{{Name}}"",""{{EntityName}}"",""{{RecordId}}"",{{ConfigJson}}); });" ; scriptTemplate = scriptTemplate.Replace("{{FieldId}}", (FieldId ?? null).ToString()); scriptTemplate = scriptTemplate.Replace("{{Name}}", Name); scriptTemplate = scriptTemplate.Replace("{{EntityName}}", EntityName); scriptTemplate = scriptTemplate.Replace("{{RecordId}}", (RecordId ?? null).ToString()); var fieldConfig = new WvFieldColorConfig() { ApiUrl = ApiUrl, CanAddValues = Access == FieldAccess.FullAndCreate ? true : false }; scriptTemplate = scriptTemplate.Replace("{{ConfigJson}}", JsonConvert.SerializeObject(fieldConfig)); initScript.InnerHtml.AppendHtml(jsCompressor.Compress(scriptTemplate)); output.PostContent.AppendHtml(initScript); #endregion } else if (Access == FieldAccess.ReadOnly) { var divEl = new TagBuilder("div"); divEl.AddCssClass("input-group"); var inputEl = new TagBuilder("input"); inputEl.AddCssClass("form-control erp-color"); inputEl.Attributes.Add("type", "color"); inputEl.Attributes.Add("value", (Value ?? "").ToString()); inputEl.Attributes.Add("readonly", null); var appendActionSpan = new TagBuilder("span"); appendActionSpan.AddCssClass("input-group-append"); appendActionSpan.AddCssClass("action"); var appendTextSpan = new TagBuilder("span"); appendTextSpan.AddCssClass("input-group-text"); var appendIconSpan = new TagBuilder("span"); appendIconSpan.AddCssClass("fa fa-fw fa-lock"); appendTextSpan.InnerHtml.AppendHtml(appendIconSpan); appendActionSpan.InnerHtml.AppendHtml(appendTextSpan); divEl.InnerHtml.AppendHtml(inputEl); divEl.InnerHtml.AppendHtml(appendActionSpan); output.Content.AppendHtml(divEl); } } #endregion //Finally if (SubInputEl != null) { output.PostContent.AppendHtml(SubInputEl); } return(Task.CompletedTask); }
public static IHtmlString GravatarImage(this HtmlHelper helper, string email, int size) { if (email == null) { return null; } if (size == 0) { return null; } var imgTag = new TagBuilder("img"); imgTag.Attributes.Add("src", string.Format("{0}://{1}.gravatar.com/avatar/{2}?s={3}&d=mm&r=pg", helper.ViewContext.HttpContext.Request.IsSecureConnection ? "https" : "http", helper.ViewContext.HttpContext.Request.IsSecureConnection ? "secure" : "www", MD5Hash(email.Trim().ToLower()), size.ToString() ) ); imgTag.Attributes.Add("class", "gravatar"); imgTag.Attributes.Add("alt", "Gravatar image"); imgTag.Attributes.Add("title", "Change your avatar at gravatar.com"); return new HtmlString(imgTag.ToString()); }
public static MvcHtmlString CheckboxInputField(this HtmlHelper html, string fieldName, string fieldExpression, bool? fieldValue) { StringBuilder result = new StringBuilder(); TagBuilder tagB = new TagBuilder("label"); tagB.MergeAttribute("for", fieldExpression); tagB.InnerHtml = fieldName; result.AppendLine(tagB.ToString()); tagB = new TagBuilder("input"); tagB.MergeAttribute("type", "checkbox"); tagB.MergeAttribute("id", fieldExpression); tagB.MergeAttribute("name", fieldExpression); tagB.MergeAttribute("value", "true"); if (fieldValue != null && fieldValue.Value) { tagB.MergeAttribute("checked", "checked"); } result.AppendLine(tagB.ToString()); tagB = new TagBuilder("input"); tagB.MergeAttribute("type", "hidden"); tagB.MergeAttribute("name", fieldExpression); tagB.MergeAttribute("value", "false"); result.AppendLine(tagB.ToString()); MvcHtmlString mvc = MvcHtmlString.Create(result.ToString()); return mvc; }
public LinkButton(string id, string text) { tagBuilder = new TagBuilder("a"); tagBuilder.MergeAttribute("id", id); tagBuilder.AddCssClass("easyui-linkbutton"); tagBuilder.SetInnerText(text); }
public void RenderControl(HtmlTextWriter writer) { SetTheme(); if (_version == ReCaptchaVersion.Version1) { var scriptCaptchaOptionsTag = new TagBuilder("script"); scriptCaptchaOptionsTag.Attributes.Add("type", MimeTypes.TextJavascript); scriptCaptchaOptionsTag.InnerHtml = string.Format("var RecaptchaOptions = {{ theme: '{0}', tabindex: 0 }}; ", Theme); writer.Write(scriptCaptchaOptionsTag.ToString(TagRenderMode.Normal)); var scriptLoadApiTag = new TagBuilder("script"); scriptLoadApiTag.Attributes.Add("src", string.Format(RECAPTCHA_API_URL_VERSION1, PublicKey)); writer.Write(scriptLoadApiTag.ToString(TagRenderMode.Normal)); } else if (_version == ReCaptchaVersion.Version2) { var scriptCallbackTag = new TagBuilder("script"); scriptCallbackTag.Attributes.Add("type", MimeTypes.TextJavascript); scriptCallbackTag.InnerHtml = string.Format("var onloadCallback = function() {{grecaptcha.render('{0}', {{'sitekey' : '{1}', 'theme' : '{2}' }});}};", Id, PublicKey, Theme); writer.Write(scriptCallbackTag.ToString(TagRenderMode.Normal)); var captchaTag = new TagBuilder("div"); captchaTag.Attributes.Add("id", Id); writer.Write(captchaTag.ToString(TagRenderMode.Normal)); var scriptLoadApiTag = new TagBuilder("script"); scriptLoadApiTag.Attributes.Add("src", RECAPTCHA_API_URL_VERSION2 + (string.IsNullOrEmpty(Language) ? "" : string.Format("&hl={0}", Language))); scriptLoadApiTag.Attributes.Add("async", null); scriptLoadApiTag.Attributes.Add("defer", null); writer.Write(scriptLoadApiTag.ToString(TagRenderMode.Normal)); } }
public static MvcHtmlString NavigationListItemRouteLink(this HtmlHelper html, NamedRoute route) { var li = new TagBuilder("li") { InnerHtml = html.RouteLink(route.DisplayName, route.Name).ToString() }; if (CurrentRouteMatchesName(html, route.Name)) { li.AddCssClass("active"); } if (route.Children.Count() > 0) { //TODO: create a UL of child routes here. li.AddCssClass("dropdown"); li.InnerHtml = "<a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">" + route.DisplayName +"<b class=\"caret\"></b></a>"; var ul = new TagBuilder("ul"); ul.AddCssClass("dropdown-menu"); foreach (var child in route.Children) { var childLi = new TagBuilder("li"); childLi.InnerHtml = html.RouteLink(child.DisplayName, child.Name).ToString(); ul.InnerHtml += childLi.ToString(); } //that would mean we need to make some quick li.InnerHtml = "<a href='#' class='dropdown-toggle' data-toggle='dropdown'>"+route.DisplayName + " <b class='caret'></b></a>" + ul.ToString(); } return MvcHtmlString.Create(li.ToString(TagRenderMode.Normal)); }
public static MvcHtmlString History(this HtmlHelper html, int count, object domainObject = null, bool clearAll = false) { if (domainObject != null && !(domainObject is FindViewModel)) { string url = html.Object(html.ObjectTitle(domainObject).ToString(), IdHelper.ViewAction, domainObject).ToString(); html.ViewContext.HttpContext.Session.AddToCache(domainObject, url, ObjectCache.ObjectFlag.BreadCrumb); } List<string> urls = html.ViewContext.HttpContext.Session.AllCachedUrls(ObjectCache.ObjectFlag.BreadCrumb).ToList(); int sizeCache = urls.Count(); int skip = sizeCache > count ? sizeCache - count : 0; urls = urls.Skip(skip).ToList(); var tag = new TagBuilder("div"); tag.AddCssClass(IdHelper.HistoryContainerName); foreach (string url in urls) { tag.InnerHtml += url; } if (urls.Any()) { tag.InnerHtml += html.ControllerAction(MvcUi.Clear, IdHelper.ClearHistoryAction, IdHelper.HomeName, IdHelper.ClearButtonClass, "", new RouteValueDictionary(new { clearAll })); } return MvcHtmlString.Create(tag.ToString()); }
public static string InfoSpeakSpan(string aCssClass) { var myInfoSpeakSpan = new TagBuilder("span"); myInfoSpeakSpan.AddCssClass(aCssClass); myInfoSpeakSpan.InnerHtml = " "; return myInfoSpeakSpan.ToString(); }