public ZoneHelper WrapIn(string tagName, object attributes) { Wrapper = new System.Web.Mvc.TagBuilder(tagName); Wrapper.MergeAttributes(new RouteValueDictionary(attributes)); return this; }
private static string TableCellCheckBox(ModelMetadata metaData, string fieldName) { StringBuilder html = new StringBuilder(); // Checkbox System.Web.Mvc.TagBuilder checkbox = new System.Web.Mvc.TagBuilder("input"); checkbox.MergeAttribute("type", "checkbox"); checkbox.MergeAttribute("name", fieldName); checkbox.MergeAttribute("id", fieldName); //checkbox.MergeAttribute("value", "true"); checkbox.MergeAttribute("disabled", "disabled"); checkbox.MergeAttribute("class", "checkbox"); if (metaData.Model != null && (bool)metaData.Model) { checkbox.MergeAttribute("checked", "checked"); } html.Append(checkbox.ToString(TagRenderMode.SelfClosing)); // Build additional hidden input to address scenario where // unchecked checkboxes are not sent in the request. //System.Web.Mvc.TagBuilder hidden = new System.Web.Mvc.TagBuilder("input"); //hidden.MergeAttribute("type", "hidden"); //hidden.MergeAttribute("name", fieldName); //checkbox.MergeAttribute("id", fieldName); //hidden.MergeAttribute("value", "false"); //html.Append(hidden.ToString(TagRenderMode.SelfClosing)); // Table cell return(html.ToString()); }
public Displayable WrapIn(string tagName, object attributes) { Wrapper = new System.Web.Mvc.TagBuilder(tagName); Wrapper.MergeAttributes(new RouteValueDictionary(attributes)); return(this); }
/// <summary> /// Return the html for a table cell representing a date in the calendar. /// </summary> /// <param name="date"> /// The date to display. /// </param> /// <param name="isSelected"> /// A value indicating if the date is selected in the calendar. /// </param> /// <param name="canSelect"> /// A value indicating if the date can be selected. /// </param> private static string Day(DateTime date, bool isSelected, bool canSelect) { // Construct container System.Web.Mvc.TagBuilder day = new System.Web.Mvc.TagBuilder("div"); day.InnerHtml = date.Day.ToString(); // Construct table cell System.Web.Mvc.TagBuilder cell = new System.Web.Mvc.TagBuilder("td"); if (!canSelect) { cell.AddCssClass("disabledDay"); } else if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) { cell.AddCssClass("weekendDay"); } else { cell.AddCssClass("workingDay"); } if (isSelected) { cell.AddCssClass("selectedDay"); } cell.InnerHtml = day.ToString(); // Return the html return(cell.ToString()); }
protected override void BuildControl(System.Web.Mvc.TagBuilder builder, Products.CustomFieldDefinition field, string value, object htmlAttributes, System.Web.Mvc.ViewContext viewContext) { builder.AddCssClass("form-list"); var itemsHtml = new StringBuilder(); var i = 0; foreach (var item in field.SelectionItems) { itemsHtml.AppendLine("<li>"); var radioId = field.Name + "_" + i; var radio = new TagBuilder("input"); radio.MergeAttribute("id", radioId); radio.MergeAttribute("type", "radio"); radio.MergeAttribute("name", field.Name); radio.MergeAttribute("value", item.Value); var label = new TagBuilder("label"); label.InnerHtml = item.Text; label.AddCssClass("inline"); label.MergeAttribute("for", radioId); itemsHtml.AppendLine(radio.ToString(TagRenderMode.SelfClosing)); itemsHtml.AppendLine(label.ToString()); itemsHtml.AppendLine("</li>"); i++; } builder.InnerHtml = itemsHtml.ToString(); base.BuildControl(builder, field, value, htmlAttributes, viewContext); }
/// <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 IHtmlString ReactInitJavaScript(string script) { var tag = new System.Web.Mvc.TagBuilder("script") { InnerHtml = script }; return new HtmlString(tag.ToString()); }
public static IHtmlString ReactInitJavaScript(string script) { var tag = new System.Web.Mvc.TagBuilder("script") { InnerHtml = script }; return(new HtmlString(tag.ToString())); }
public ZoneHelper WrapIn(string tagName, object attributes, string innerHtml = null) { Wrapper = (ci) => { var w = new System.Web.Mvc.TagBuilder(tagName); w.MergeAttributes(new RouteValueDictionary(attributes)); w.InnerHtml = innerHtml; return(w); }; return(this); }
public ZoneHelper WrapIn(string tagName, object attributes, string innerHtml = null) { Wrapper = (ci) => { var w = new System.Web.Mvc.TagBuilder(tagName); w.MergeAttributes(new RouteValueDictionary(attributes)); w.InnerHtml = innerHtml; return w; }; return this; }
/// <summary> /// Returns the html for the date picker display text (visible when the datepicker does not have focus) /// </summary> /// <param name="metadata"> /// The meta data of the property to display the date for. /// </param> private static string DatePickerText(ModelMetadata metadata) { System.Web.Mvc.TagBuilder text = new System.Web.Mvc.TagBuilder("div"); text.AddCssClass("datepicker-text"); // Add essential stype properties text.MergeAttribute("style", "position:absolute;z-index:-1000;"); if (metadata.Model != null) { text.InnerHtml = ((DateTime)metadata.Model).ToLongDateString(); } // Return the html return(text.ToString()); }
private static string CreateTableString(string header, string body, GenericTableVModel model) { StringBuilder html = new StringBuilder(); System.Web.Mvc.TagBuilder table = new System.Web.Mvc.TagBuilder("table"); table.MergeAttribute("class", model.Setting.Class); table.MergeAttribute("id", model.Setting.Id); table.InnerHtml = header + body; html.Append(table.ToString()); return(html.ToString()); }
/// <summary> /// Returns the html for the table header displaying the selected month, navigation buttons /// and days of the week. /// </summary> /// <param name="date"> /// A date in month to display. /// </param> /// <param name="minDate"> /// The minimum date that can be seleccted. /// </param> /// <param name="maxDate"> /// The maximum date that can be seleccted. /// </param> private static string CalendarHeader(DateTime date, DateTime?minDate, DateTime?maxDate) { StringBuilder html = new StringBuilder(); // Add month label and navigation buttons html.Append(MonthHeader(date, minDate, maxDate)); // Add day of week labels html.Append(WeekHeader()); // Construct table header System.Web.Mvc.TagBuilder header = new System.Web.Mvc.TagBuilder("thead"); header.InnerHtml = html.ToString(); // Return the html return(header.ToString()); }
/// <summary> /// Returns the html for the date picker input, including validation attributes and message. /// </summary> /// <param name="helper"> /// The html helper. /// </param> /// <param name="metadata"> /// The meta data of the property to display the date for. /// </param> /// <param name="name"> /// The fully qualified name of the property. /// </param> /// <returns></returns> private static string DatePickerInput(System.Web.Mvc.HtmlHelper helper, System.Web.Mvc.ModelMetadata metadata, string name) { // Construct the input System.Web.Mvc.TagBuilder input = new System.Web.Mvc.TagBuilder("input"); input.AddCssClass("datepicker-input"); input.MergeAttribute("type", "text"); input.MergeAttribute("id", System.Web.Mvc.HtmlHelper.GenerateIdFromName(name)); input.MergeAttribute("autocomplete", "off"); input.MergeAttribute("name", name); input.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(name, metadata)); if (metadata.Model != null) { input.MergeAttribute("value", ((DateTime)metadata.Model).ToShortDateString()); } // Return the html return(input.ToString()); }
public static MvcHtmlString MarkedAuthors(this HtmlHelper helper, List <Author> authors, string search) { string result = ""; for (int i = 0; i < authors.Count; i++) { TagBuilder a = new System.Web.Mvc.TagBuilder("a"); a.Attributes["href"] = "#"; a.InnerHtml = authors[i].Name; result += a.ToString(); if (i > 0) { result += ", "; } } return(MvcHtmlString.Create(result)); }
/// <summary> /// Returns the html for a table cell with a navigation button. /// </summary> /// <param name="className"> /// The class name to apply to the button. /// </param> /// <param name="hide"> /// A value indicating if the button should be rendered as hidden. /// </param> private static string NavigationButton(string className, bool hide) { // Build the button System.Web.Mvc.TagBuilder button = new System.Web.Mvc.TagBuilder("button"); button.AddCssClass(className); button.MergeAttribute("type", "button"); button.MergeAttribute("tabindex", "-1"); if (hide) { button.MergeAttribute("style", "display:none;"); } // Construct the table cell System.Web.Mvc.TagBuilder cell = new System.Web.Mvc.TagBuilder("th"); cell.InnerHtml = button.ToString(); // Return the html return(cell.ToString()); }
/// <summary> /// Return the html for the table body representing a month in the calendar. /// </summary> /// <param name="date"> /// A date in the month to display. /// </param> /// <param name="isSelected"> /// A value indicating if the date should be marked as selected. /// </param> /// <param name="minDate"> /// The minimum date that can be seleccted. /// </param> /// <param name="maxDate"> /// The maximum date that can be seleccted. /// </param> private static string Month(DateTime date, bool isSelected, DateTime?minDate, DateTime?maxDate) { // Get the first and last days of the month DateTime firstOfMonth = date.FirstOfMonth(); DateTime lastOfMonth = date.LastOfMonth(); // Get the first date to display in the calendar (may be in the previous month) DateTime startDate = firstOfMonth.AddDays(-(int)firstOfMonth.DayOfWeek); // Build a table containing 6 rows (weeks) x 7 columns (day of week) StringBuilder month = new StringBuilder(); StringBuilder html = new StringBuilder(); for (int i = 0; i < 42; i++) { // Get the date to display DateTime displayDate = startDate.AddDays(i); // Determine if the date is selectable bool canSelect = true; if (displayDate.Month != date.Month) { canSelect = false; } else if (minDate.HasValue && displayDate < minDate.Value) { canSelect = false; } else if (maxDate.HasValue && displayDate > maxDate.Value) { canSelect = false; } html.Append(Day(displayDate, isSelected && date == displayDate, canSelect)); if (i % 7 == 6) { // Its the end of the week, so start a new row in the table System.Web.Mvc.TagBuilder week = new System.Web.Mvc.TagBuilder("tr"); week.InnerHtml = html.ToString(); month.Append(week.ToString()); html.Clear(); } } // Construct the table body System.Web.Mvc.TagBuilder calendar = new System.Web.Mvc.TagBuilder("tbody"); calendar.AddCssClass("calendar-dates"); calendar.InnerHtml = month.ToString(); // Return the html return(calendar.ToString()); }
public static IHtmlString GoogleCaptcha(this HtmlHelper helper) { var publicSiteKey = ConfigurationManager.AppSettings["GoogleRecaptchaSiteKey"]; var mvcHtmlString = new System.Web.Mvc.TagBuilder("div") { Attributes = { new KeyValuePair <string, string>("class", "g-recaptcha"), new KeyValuePair <string, string>("data-sitekey", publicSiteKey) } }; const string googleCaptchaScript = "<script src='https://www.google.com/recaptcha/api.js'></script>"; var renderedCaptcha = mvcHtmlString.ToString(TagRenderMode.Normal); return(MvcHtmlString.Create($"{googleCaptchaScript}{renderedCaptcha}")); }
public static IDisposable BeginAsyncAction(this HtmlHelper helper, string actionName, RouteValueDictionary routeValues) { var id = "async" + Guid.NewGuid().ToString().Replace('-', '_'); var url = new UrlHelper(helper.ViewContext.RequestContext).Action(actionName, routeValues); var tag = new System.Web.Mvc.TagBuilder("div"); tag.Attributes["id"] = id; tag.AddCssClass("async loading"); helper.ViewContext.Writer.Write(tag.ToString(TagRenderMode.StartTag)); var asyncLoadScript = string.Format(@"<script type='text/javascript'>//<![CDATA[ jQuery(document).ready(function(){{jQuery('#{0}').load('{1}');}});//]]></script>", id, url); var end = tag.ToString(TagRenderMode.EndTag) + asyncLoadScript; return new WritesOnDispose(helper, end); }
/// <summary> /// Returns the html for a table row displaying the days of the week. /// </summary> private static string WeekHeader() { // Build a table cell for each day of the week string[] daysOfWeek = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; StringBuilder html = new StringBuilder(); for (int i = 0; i < 7; i++) { System.Web.Mvc.TagBuilder day = new System.Web.Mvc.TagBuilder("td"); day.InnerHtml = daysOfWeek[i]; html.Append(day.ToString()); } // Construct the table row System.Web.Mvc.TagBuilder week = new System.Web.Mvc.TagBuilder("tr"); week.AddCssClass("calendar-daysOfWeek"); week.InnerHtml = html.ToString(); // Return the html return(week.ToString()); }
public static IDisposable BeginAsyncAction(this HtmlHelper helper, string actionName, RouteValueDictionary routeValues) { var id = "async" + Guid.NewGuid().ToString().Replace('-', '_'); var url = new UrlHelper(helper.ViewContext.RequestContext).Action(actionName, routeValues); var tag = new System.Web.Mvc.TagBuilder("div"); tag.Attributes["id"] = id; tag.AddCssClass("async loading"); helper.ViewContext.Writer.Write(tag.ToString(TagRenderMode.StartTag)); var asyncLoadScript = string.Format(@"<script type='text/javascript'>//<![CDATA[ jQuery(document).ready(function(){{jQuery('#{0}').load('{1}');}});//]]></script>", id, url); var end = tag.ToString(TagRenderMode.EndTag) + asyncLoadScript; return(new WritesOnDispose(helper, end)); }
public static MvcHtmlString SideBarSecureActionLink(this HtmlHelper htmlHelper, string linkText, string url, string cssClass, string spanCssClass, params string[] permission) { var hasPermission = permission.Any(HttpContext.Current.User.IsInRole); if (!hasPermission) { return(MvcHtmlString.Empty); } var a = new TagBuilder("a"); a.Attributes.Add("href", url); a.AddCssClass(cssClass); var span = new TagBuilder("span"); span.AddCssClass(spanCssClass); a.InnerHtml = span.ToString(TagRenderMode.Normal) + linkText; return(MvcHtmlString.Create(a.ToString())); }
/// <summary> /// Writes an opening <![CDATA[ <a> ]]> tag to the response if the shouldWriteLink argument is true. /// Returns a ConditionalLink object which when disposed will write a closing <![CDATA[ </a> ]]> tag /// to the response if the shouldWriteLink argument is true. /// </summary> public static ConditionalLink BeginConditionalLink(this HtmlHelper helper, bool shouldWriteLink, IHtmlString url, string title = null, string cssClass = null) { if (shouldWriteLink) { var linkTag = new System.Web.Mvc.TagBuilder("a"); linkTag.Attributes.Add("href", url.ToHtmlString()); if (!string.IsNullOrWhiteSpace(title)) { linkTag.Attributes.Add("title", helper.Encode(title)); } if (!string.IsNullOrWhiteSpace(cssClass)) { linkTag.Attributes.Add("class", cssClass); } helper.ViewContext.Writer.Write(linkTag.ToString(TagRenderMode.StartTag)); } return new ConditionalLink(helper.ViewContext, shouldWriteLink); }
/// <summary> /// Writes an opening <![CDATA[ <a> ]]> tag to the response if the shouldWriteLink argument is true. /// Returns a ConditionalLink object which when disposed will write a closing <![CDATA[ </a> ]]> tag /// to the response if the shouldWriteLink argument is true. /// </summary> public static ConditionalLink BeginConditionalLink(this HtmlHelper helper, bool shouldWriteLink, IHtmlString url, string title = null, string cssClass = null) { if (shouldWriteLink) { var linkTag = new System.Web.Mvc.TagBuilder("a"); linkTag.Attributes.Add("href", url.ToHtmlString()); if (!string.IsNullOrWhiteSpace(title)) { linkTag.Attributes.Add("title", helper.Encode(title)); } if (!string.IsNullOrWhiteSpace(cssClass)) { linkTag.Attributes.Add("class", cssClass); } helper.ViewContext.Writer.Write(linkTag.ToString(TagRenderMode.StartTag)); } return(new ConditionalLink(helper.ViewContext, shouldWriteLink)); }
//public static IHtmlContent GetList(this IHtmlHelper helper) // { // System.Web.Mvc.TagBuilder li = new System.Web.Mvc.TagBuilder("li"); // var listHtml = new HtmlContentBuilder(); // listHtml.AppendHtml("<li class='dropdown'>"); // listHtml.AppendHtml("<a class='fa fa - user' data-toggle='dropdown'"); // listHtml.AppendHtml("<span class='caret'>"); // listHtml.AppendHtml("</span>"); // listHtml.AppendHtml("</a>"); // listHtml.AppendHtml("<ul class='dropdown-menu'>"); // listHtml.AppendHtml("<li>"); // listHtml.AppendHtml("<a>"); // listHtml.AppendHtml(helper.ActionLink("foo", "bar", "example")); // listHtml.AppendHtml("</a>"); // listHtml.AppendHtml("</li>"); // listHtml.AppendHtml("</ul>"); // listHtml.AppendHtml("</li>"); // return listHtml; // } /*public static IHtmlContent GenerateInput(this IHtmlHelper<TModel> helper) * { * var tb = new TagBuilder("input"); * * tb.TagRenderMode = TagRenderMode.SelfClosing; * tb.MergeAttribute("name", this.GetIdentity()); * tb.MergeAttribute("type", "hidden"); * tb.MergeAttribute("value", this.GetSelectedItem()?.Value); * return tb; * }*/ // <div class="form-group"> // <label class="col-sm-2 control-label"><span class="input-group-text" id="inputGroup-sizing-default">@Html.LabelFor(x => x.Name)</span></label> // <div class="col-sm-10"> // @Html.TextBoxFor(x => x.Name, new { @class = "form-control" }) // <span asp-validation-for="Name" /> // </div> //</div> public static IHtmlContent LabeledTextBoxFor <TModel, TResult>(this IHtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TResult> > expression) { var builder = new System.Web.Mvc.TagBuilder("div"); builder.AddCssClass("form-group"); var label = new System.Web.Mvc.TagBuilder("label"); label.AddCssClass("col-sm-2 control-label"); label.Attributes.Add("id", ""); // builder.InnerHtml += label.toHtml var textBoxFor = htmlHelper.TextBoxFor(expression); var labelFor = htmlHelper.LabelFor(expression); builder.InnerHtml = "polof"; return(new HtmlString(builder.ToString())); }
/// <summary> /// Return the html for a calendar. /// </summary> /// <param name="date"> /// A date in the month to display. /// </param> /// <param name="isSelected"> /// A value indicating if the date should be marked as selected. /// </param> /// <param name="minDate"> /// The minimum date that can be selected. /// </param> /// <param name="maxDate"> /// The maximum date that can be selected. /// </param> private static string Calendar(DateTime date, bool isSelected, DateTime?minDate, DateTime?maxDate) { StringBuilder html = new StringBuilder(); // Add header html.Append(CalendarHeader(date, minDate, maxDate)); // Add body html.Append(Month(date, isSelected, minDate, maxDate)); // Construct table System.Web.Mvc.TagBuilder table = new System.Web.Mvc.TagBuilder("table"); table.InnerHtml = html.ToString(); // Construct inner container that can optionally be styled as position:absolute if within a date picker System.Web.Mvc.TagBuilder inner = new System.Web.Mvc.TagBuilder("div"); inner.AddCssClass("container"); inner.InnerHtml = table.ToString(); // Construct outer container System.Web.Mvc.TagBuilder outer = new System.Web.Mvc.TagBuilder("div"); outer.AddCssClass("calendar"); outer.InnerHtml = inner.ToString(); // Return the html return(outer.ToString()); }
public static IHtmlContent File <TModel, TResult>(this IHtmlHelper <IModel> htmlHelper, Expression <Func <TModel, TResult> > expression, string id) { var div = new System.Web.Mvc.TagBuilder("div"); div.AddCssClass("form-control"); var label = new System.Web.Mvc.TagBuilder("label"); label.AddCssClass("col-sm-2 control-label"); var span = new System.Web.Mvc.TagBuilder("span"); span.AddCssClass("input-group-text"); span.Attributes.Add("id", "inputGroup-sizing-default"); // var textBoxFor = htmlHelper.TextBoxFor(expression); // var labelFor = htmlHelper.LabelFor(expression); System.Web.Mvc.TagBuilder tb = new System.Web.Mvc.TagBuilder("input"); tb.Attributes.Add("type", "file"); tb.Attributes.Add("id", id); return(new HtmlString(tb.ToString())); }
/// <summary> /// Returns the html for the table header row displaying the current month and navigation buttons. /// </summary> /// <param name="date"> /// A date in the month to display. /// </param> /// <param name="minDate"> /// The minimum date that can be selected. /// </param> /// <param name="maxDate"> /// The maximmum date that can be selected. /// </param> private static string MonthHeader(DateTime date, DateTime?minDate, DateTime?maxDate) { StringBuilder html = new StringBuilder(); // Add previous month navigation button bool hidePrevious = minDate.HasValue && date.FirstOfMonth() <= minDate.Value; html.Append(NavigationButton("previousButton", hidePrevious)); // Add month label System.Web.Mvc.TagBuilder label = new System.Web.Mvc.TagBuilder("span"); label.InnerHtml = string.Format("{0:MMMM yyyy}", date); System.Web.Mvc.TagBuilder cell = new System.Web.Mvc.TagBuilder("th"); cell.MergeAttribute("colspan", "5"); cell.InnerHtml = label.ToString(); html.Append(cell); // Add next month navigation button bool hideNext = maxDate.HasValue && date.LastOfMonth() >= maxDate.Value; html.Append(NavigationButton("nextButton", hideNext)); // Construct header row System.Web.Mvc.TagBuilder header = new System.Web.Mvc.TagBuilder("tr"); header.InnerHtml = html.ToString(); // Return the html return(header.ToString()); }
internal static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode) { Debug.Assert(tagBuilder != null); return(new MvcHtmlString(tagBuilder.ToString(renderMode))); }
public static MvcHtmlString LsCheckBox <TModel, TValue>( this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, bool isEnabled = true, bool showLabel = true, bool isCheckByDefault = true) { var metaData = ModelMetadata.FromLambdaExpression(expression, html.ViewData); string propertyName = metaData.PropertyName; string displayName = metaData.DisplayName ?? propertyName; string disabled = isEnabled ? "" : "disabled"; var value = metaData.Model?.ToString(); bool isChecked = false; if (value == null) { if (isCheckByDefault) { isChecked = true; } } else { if (value == "True") { isChecked = true; } } var OuterDiv = new TagBuilder("div"); OuterDiv.AddCssClass("form-group row m-form__group"); var fieldLabel = new TagBuilder("label"); if (showLabel) { fieldLabel.Attributes.Add("for", propertyName); fieldLabel.AddCssClass("col-form-label col-md-2"); fieldLabel.InnerHtml = displayName; OuterDiv.InnerHtml = fieldLabel.ToString(); } bool hasError = false; var validationSpan = new TagBuilder("span"); validationSpan.AddCssClass("form-control-feedback"); var modelState = html.ViewData.ModelState; if (modelState[propertyName] != null) { var error = modelState[propertyName].Errors.FirstOrDefault(); if (error != null) { hasError = true; validationSpan.InnerHtml = error.ErrorMessage; } } if (hasError) { OuterDiv.AddCssClass("has-danger"); } var inputWrapper = new System.Web.Mvc.TagBuilder("div"); inputWrapper.AddCssClass("col-md-8"); var inputWrapperChild = new TagBuilder("div"); inputWrapperChild.AddCssClass("checkbox m-switch"); var inputWrapperSpan = new TagBuilder("span"); inputWrapperSpan.AddCssClass("m-switch m-switch--icon"); var inputWrapperLabel = new TagBuilder("label"); var input = new TagBuilder("input"); input.Attributes.Add("id", propertyName); input.Attributes.Add("name", propertyName); input.Attributes.Add("type", "checkbox"); input.Attributes.Add("value", "true"); if (!isEnabled) { input.Attributes.Add("disabled", "true"); } if (isChecked) { input.Attributes.Add("checked", null); } inputWrapperLabel.InnerHtml = input.ToString() + "<input name='" + propertyName + "' type='hidden' value='false' />" + " <span></span>"; inputWrapperSpan.InnerHtml = inputWrapperLabel.ToString(); inputWrapperChild.InnerHtml = inputWrapperSpan.ToString() + validationSpan.ToString(); inputWrapper.InnerHtml = inputWrapperChild.ToString(); OuterDiv.InnerHtml = fieldLabel.ToString() + inputWrapper.ToString(); return(MvcHtmlString.Create(OuterDiv.ToString())); }
/// <summary> /// Generates the HTML markup corresponding to a list of checkboxes. /// </summary> /// <typeparam name="TModel">The type of the model</typeparam> /// <typeparam name="T">The type of the elements of the enumeration. Use simple types</typeparam> /// <param name="htmlHelper"></param> /// <param name="expression">The lambda expression that yields an enumeration of Ts</param> /// <param name="namePrefix">Prefix to be used by the name for the generated checkboxes</param> /// <param name="items">List of available options to be displayed</param> /// <param name="htmlAttributes">An object whose properties will become attributes for the HTML main container element</param> /// <param name="cols">Number of columns in which the list will be arranged. Valid values range lies between 1 and 12</param> /// <returns></returns> public static MvcHtmlString MultiSelectFor<TModel, T>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IEnumerable<T>>> expression, IEnumerable<SelectListItem> items, object htmlAttributes, int cols = 1 ) { cols = (cols < 1 || cols > 12) ? 1 : cols; int rows = items.Count() % cols == 0 ? items.Count() / cols : 1 + items.Count() / cols; TagBuilder mainContainer = new TagBuilder("div"); if(htmlAttributes != null) { foreach(PropertyInfo prop in htmlAttributes.GetType().GetProperties()) { mainContainer.Attributes.Add(prop.Name, prop.GetValue(htmlAttributes).ToString()); } } TagBuilder grid = new TagBuilder("div"); grid.Attributes.Add("style", $"display: grid; grid.template-columns: {cols}; grid-template-rows: {rows}"); ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); string prefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix; string cboxName = String.IsNullOrWhiteSpace(prefix) ? modelMetadata.PropertyName : $"{prefix}.{modelMetadata.PropertyName}"; int index = 0; StringBuilder gridContentBuilder = new StringBuilder(); foreach(SelectListItem item in items) { int currentCol = 1 + index % cols; int currentRow = 1 + index / cols; TagBuilder div = new TagBuilder("div"); div.Attributes.Add("style", $"grid-column-start: {currentCol}; grid-row-start: {currentRow}"); TagBuilder checkbox = new TagBuilder("input"); checkbox.Attributes.Add("type", "checkbox"); checkbox.Attributes.Add("name", cboxName); checkbox.Attributes.Add("value", item.Value); if(item.Selected) { checkbox.Attributes.Add("checked", "checked"); } checkbox.GenerateId($"{cboxName}_{item.Value}"); TagBuilder label = new TagBuilder("label"); label.Attributes.Add("for", checkbox.Attributes["id"]); label.SetInnerText(item.Text); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(checkbox.ToString(TagRenderMode.SelfClosing)); stringBuilder.AppendLine(label.ToString(TagRenderMode.Normal)); div.InnerHtml = stringBuilder.ToString(); gridContentBuilder.AppendLine(div.ToString(TagRenderMode.Normal)); index++; } grid.InnerHtml = gridContentBuilder.ToString(); mainContainer.InnerHtml = grid.ToString(TagRenderMode.Normal); return new MvcHtmlString(mainContainer.ToString(TagRenderMode.Normal)); }
public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func <int, string> pageUrl) { StringBuilder stringBuilder = new StringBuilder(); if (pagingInfo.TotalPages != 0) { TagBuilder tagBuilder = new TagBuilder("a") { InnerHtml = "Previous" }; if (pagingInfo.CurrentPage == 1) { tagBuilder.MergeAttribute("class", "prev-disabled"); } else { tagBuilder.MergeAttribute("href", pageUrl(pagingInfo.CurrentPage - 1)); } stringBuilder.Append(tagBuilder.ToString()); if (pagingInfo.TotalPages >= 1) { TagBuilder tagBuilder1 = new TagBuilder("a") { InnerHtml = "1" }; tagBuilder1.MergeAttribute("href", pageUrl(1)); if (pagingInfo.CurrentPage == 1) { tagBuilder1.MergeAttribute("class", "current"); } stringBuilder.Append(tagBuilder1.ToString()); } if (pagingInfo.TotalPages >= 2) { TagBuilder tagBuilder2 = new TagBuilder("a") { InnerHtml = "2" }; tagBuilder2.MergeAttribute("href", pageUrl(2)); if (pagingInfo.CurrentPage == 2) { tagBuilder2.MergeAttribute("class", "current"); } stringBuilder.Append(tagBuilder2.ToString()); } if (pagingInfo.CurrentPage > 5 && pagingInfo.TotalPages != 6) { TagBuilder tagBuilder3 = new TagBuilder("span") { InnerHtml = "..." }; tagBuilder3.MergeAttribute("class", "text"); stringBuilder.Append(tagBuilder3.ToString()); } if (pagingInfo.CurrentPage > 2) { int currentPage = pagingInfo.CurrentPage; } if (pagingInfo.CurrentPage <= 5) { for (int i = 3; i < 8 && i <= pagingInfo.TotalPages; i++) { TagBuilder tagBuilder4 = new TagBuilder("a") { InnerHtml = i.ToString() }; tagBuilder4.MergeAttribute("href", pageUrl(i)); if (i == pagingInfo.CurrentPage) { tagBuilder4.MergeAttribute("class", "current"); } stringBuilder.Append(tagBuilder4.ToString()); } if (pagingInfo.TotalPages > 7) { TagBuilder tagBuilder5 = new TagBuilder("span") { InnerHtml = "..." }; tagBuilder5.MergeAttribute("class", "text"); stringBuilder.Append(tagBuilder5.ToString()); } } if (pagingInfo.CurrentPage > 5 && pagingInfo.CurrentPage + 5 > pagingInfo.TotalPages) { int totalPages = pagingInfo.TotalPages - 4; if (totalPages == 2) { totalPages++; } for (int j = totalPages; j <= pagingInfo.TotalPages; j++) { TagBuilder tagBuilder6 = new TagBuilder("a") { InnerHtml = j.ToString() }; tagBuilder6.MergeAttribute("href", pageUrl(j)); if (j == pagingInfo.CurrentPage) { tagBuilder6.MergeAttribute("class", "current"); } stringBuilder.Append(tagBuilder6.ToString()); } } if (pagingInfo.CurrentPage > 5 && pagingInfo.CurrentPage + 5 <= pagingInfo.TotalPages) { for (int k = pagingInfo.CurrentPage; k < pagingInfo.CurrentPage + 5; k++) { TagBuilder tagBuilder7 = new TagBuilder("a") { InnerHtml = (k - 2).ToString() }; tagBuilder7.MergeAttribute("href", pageUrl(k - 2)); if (k == pagingInfo.CurrentPage + 2) { tagBuilder7.MergeAttribute("class", "current"); } stringBuilder.Append(tagBuilder7.ToString()); } TagBuilder tagBuilder8 = new TagBuilder("span") { InnerHtml = "..." }; tagBuilder8.MergeAttribute("class", "text"); stringBuilder.Append(tagBuilder8.ToString()); } TagBuilder tagBuilder9 = new TagBuilder("a") { InnerHtml = "Next" }; if (pagingInfo.CurrentPage == pagingInfo.TotalPages) { tagBuilder9.MergeAttribute("class", "next-disabled"); } else { tagBuilder9.MergeAttribute("href", pageUrl(pagingInfo.CurrentPage + 1)); } stringBuilder.Append(tagBuilder9.ToString()); } return(MvcHtmlString.Create(stringBuilder.ToString())); }
public static IHtmlString Select2For <TModel, TValue>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TValue> > expression, string format, IDictionary <string, object> htmlAttributes, bool multiple) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); string name = ExpressionHelper.GetExpressionText(expression); string value = string.Empty; string dataPlaceHolder = string.Empty; if (metadata.Model != null) { if ((metadata.ModelType == typeof(Guid)) && ((Guid)metadata.Model == Guid.Empty)) { value = string.Empty; } else { value = metadata.Model.ToString(); } } string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException("Cannot find fullName."); } System.Web.Mvc.TagBuilder tagBuilder = null; tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden)); tagBuilder.MergeAttribute("name", !multiple ? fullName : fullName + "[]", true); if (multiple) { tagBuilder.MergeAttribute("multiple", "", true); } if (metadata.AdditionalValues != null) { if (metadata.AdditionalValues.ContainsKey(DATA_PLACEHOLDER)) { tagBuilder.MergeAttribute(DATA_PLACEHOLDER, metadata.AdditionalValues[DATA_PLACEHOLDER] as string); } if (metadata.AdditionalValues.ContainsKey(DATA_OPTION)) { string fieldName = metadata.AdditionalValues[DATA_OPTION] as string; var parentType = metadata.ContainerType; var parentMetaData = ModelMetadataProviders.Current .GetMetadataForProperties(htmlHelper.ViewData.Model, parentType); var dataOptionValue = (string)parentMetaData.FirstOrDefault(p => p.PropertyName == fieldName).Model; tagBuilder.MergeAttribute(DATA_OPTION, dataOptionValue ?? ""); } //if (multiple && metadata.AdditionalValues.ContainsKey(DATA_SPLIT)) //{ // tagBuilder.MergeAttribute(DATA_SPLIT, metadata.AdditionalValues[DATA_SPLIT].ToString()); //} } string valueParameter = htmlHelper.FormatValue(value, format); // bool usedModelState = false; bool useViewData = false; bool isExplicitValue = true; string attemptedValue = string.Empty; ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState)) { if (modelState.Value != null) { attemptedValue = (string)modelState.Value.ConvertTo(typeof(string), null /* culture */); } if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } var validationAttribs = htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata); tagBuilder.MergeAttributes(validationAttribs); // tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty), metadata)); tagBuilder.MergeAttribute("value", value ?? ((useViewData) ? attemptedValue : valueParameter), isExplicitValue); tagBuilder.GenerateId(fullName); return(MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing))); }