/// <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());; }
/// <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()); }
/// <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()); }
/// <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()); }
/// <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()); }
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())); }
//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())); }
private static MvcHtmlString BootstrapInputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, IDictionary <string, object> htmlAttributes, string blockHelpText) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException("Value cannot be null or empty.", "name"); } TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(inputType)); tagBuilder.MergeAttribute("name", fullName, true); string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture); bool usedModelState = false; switch (inputType) { case InputType.CheckBox: bool?modelStateWasChecked = htmlHelper.GetModelStateValue(fullName, typeof(bool)) as bool?; if (modelStateWasChecked.HasValue) { isChecked = modelStateWasChecked.Value; usedModelState = true; } goto case InputType.Radio; case InputType.Radio: if (!usedModelState) { string modelStateValue = htmlHelper.GetModelStateValue(fullName, typeof(string)) as string; if (modelStateValue != null) { isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal); usedModelState = true; } } if (!usedModelState && useViewData) { isChecked = htmlHelper.EvalBoolean(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)htmlHelper.GetModelStateValue(fullName, typeof(string)); tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName) : 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)); 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())); } else if (!String.IsNullOrEmpty(blockHelpText)) { // Render an additional <span class="help-block"> inside // the <input ...> for the help text StringBuilder inputItemBuilder = new StringBuilder(); inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.StartTag)); TagBuilder span = new TagBuilder("span"); span.MergeAttribute("class", "help-block"); inputItemBuilder.Append(span.ToString(TagRenderMode.StartTag)); inputItemBuilder.Append(blockHelpText); inputItemBuilder.Append(span.ToString(TagRenderMode.EndTag)); inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.EndTag)); return(MvcHtmlString.Create(inputItemBuilder.ToString())); } return(new MvcHtmlString(tagBuilder.ToString(TagRenderMode.SelfClosing))); }
/// <summary> /// Validations the summary. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="groupName">Name of the group.</param> /// <param name="excludePropertyErrors">if set to <c>true</c> [exclude property errors].</param> /// <param name="message">The message.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string groupName, bool excludePropertyErrors, string message, IDictionary <string, object> htmlAttributes) { #region Validate Arguments if (htmlHelper == null) { throw new ArgumentNullException("htmlHelper"); } groupName = groupName ?? string.Empty; #endregion string[] groupNames = groupName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); if (htmlAttributes == null) { htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(null); } htmlAttributes["data-val-valgroup-name"] = groupName; object model = htmlHelper.ViewData.Model; ModelStateDictionary modelState = htmlHelper.ViewData.ModelState; bool canValidate = !modelState.ContainsKey(ValidationGroupsKey) || (groupNames.Any() && ((IEnumerable <string>)modelState[ValidationGroupsKey].Value.RawValue).Intersect(groupNames).Any()) || (!groupNames.Any()); IEnumerable <ModelState> faulted = canValidate ? GetFaultedModelStates(htmlHelper, groupNames, model) : Enumerable.Empty <ModelState>(); FormContext formContextForClientValidation = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null; if (!canValidate || !faulted.Any()) { if (formContextForClientValidation == null) { return(null); } } string str = InitializeResponseString(message); IEnumerable <ModelState> values = GetValues(htmlHelper, excludePropertyErrors, modelState, faulted); TagBuilder builder3 = AddValidationMessages(htmlHelper, values); TagBuilder tagBuilder = new TagBuilder("div"); tagBuilder.MergeAttributes <string, object>(htmlAttributes); tagBuilder.AddCssClass("validation-summary"); tagBuilder.AddCssClass(!faulted.Any() ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName); tagBuilder.InnerHtml = str + builder3.ToString(TagRenderMode.Normal); if (formContextForClientValidation != null) { if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) { if (!excludePropertyErrors) { tagBuilder.MergeAttribute("data-valmsg-summary", "true"); } } else { tagBuilder.GenerateId("validationSummary"); formContextForClientValidation.ValidationSummaryId = tagBuilder.Attributes["id"]; formContextForClientValidation.ReplaceValidationSummary = !excludePropertyErrors; } } return(new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal))); }
/// <summary> /// Create a Table Layout. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlhelper"></param> /// <param name="viewModel">Model with List to Show and Properties to Show.</param> /// <param name="withEdit">A boolean type for create a Table with Edit button</param> /// <param name="withRemove">A boolean type for create a Table with Remove button</param> /// <param name="withDetail">A boolean type for create a Table with Detail button</param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcHtmlString TableListFor <TModel, TEntity>(this HtmlHelper <TModel> htmlhelper, ITableList <TEntity> viewModel, bool withEdit = false, bool withRemove = false, bool withDetail = false, object htmlAttributes = null) where TEntity : class { TagBuilder table = new TagBuilder("table"); table.AddCssClass("table table-bordered table-hover table-responsive"); TagBuilder tr = new TagBuilder("tr"); foreach (var propertyToShow in viewModel.PropertiesToShow) { TagBuilder th = new TagBuilder("th"); th.MergeAttribute("style", "cursor: default; "); th.InnerHtml = propertyToShow.DisplayProperty != null ? propertyToShow.DisplayProperty : propertyToShow.PropertyName; tr.InnerHtml += th.ToString(); } if (withEdit) { tr.InnerHtml += HtmlExtentionsCommon.CreateTagBuilder("th", "Editar", new { style = "width: 5%; cursor: default;" }).ToString(); } if (withDetail) { tr.InnerHtml += HtmlExtentionsCommon.CreateTagBuilder("th", "Detalhes", new { style = "width: 5%; cursor: default" }).ToString(); } if (withRemove) { tr.InnerHtml += HtmlExtentionsCommon.CreateTagBuilder("th", "Remover", new { style = "width: 5%; cursor: default" }).ToString(); } TagBuilder tHead = HtmlExtentionsCommon.CreateTagBuilder("thead", tr.ToString()); TagBuilder tbody = new TagBuilder("tbody"); foreach (var item in viewModel.List) { TagBuilder trItem = new TagBuilder("tr"); var propertiesFromTheItem = item.GetType().GetProperties(); foreach (var property in propertiesFromTheItem) { PropertyToShow showThisProperty = HtmlExtentionsCommon.ShowThisProperty(property, viewModel.PropertiesToShow, item); if (showThisProperty != null) { string display = showThisProperty.DisplayProperty != null ? showThisProperty.DisplayProperty : showThisProperty.PropertyName; TagBuilder td = new TagBuilder("td"); td.InnerHtml = item.GetType().GetProperty(property.Name).GetValue(item).ToString(); td.MergeAttribute("style", "padding-top: 15px"); trItem.InnerHtml += td.ToString(); } } if (withEdit) { var button = HtmlExtentionsCommon.CreateTagBuilder("td", ButtonHtmlExtention.Button( htmlhelper, string.Empty, "btn-info col-lg-12", "glyphicon glyphicon-edit", string.Empty, HtmlButtonTypes.Button, new { data_action = "editar", data_actionId = item.GetType().GetProperty("Id").GetValue(item).ToString(), title = "Editar" } ).ToString()); trItem.InnerHtml += button.ToString(); } if (withDetail) { var button = HtmlExtentionsCommon.CreateTagBuilder("td", ButtonHtmlExtention.Button( htmlhelper, string.Empty, "btn-success col-lg-10 col-lg-offset-1", "glyphicon glyphicon-search", string.Empty, HtmlButtonTypes.Button, new { data_action = "editar", data_actionId = item.GetType().GetProperty("Id").GetValue(item).ToString(), title = "Detalhe" } ).ToString()); trItem.InnerHtml += button.ToString(); } if (withRemove) { var button = HtmlExtentionsCommon.CreateTagBuilder("td", ButtonHtmlExtention.Button( htmlhelper, string.Empty, "btn-danger col-lg-10 col-lg-offset-1", "glyphicon glyphicon-trash", string.Empty, HtmlButtonTypes.Button, new { data_action = "remover", data_actionId = item.GetType().GetProperty("Id").GetValue(item).ToString(), title = "Remover" } ).ToString()); trItem.InnerHtml += button.ToString(); } tbody.InnerHtml += trItem.ToString(); } table.InnerHtml = tHead.ToString(); table.InnerHtml += tbody.ToString(); if (htmlAttributes != null) { var anonymousObject = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); if (anonymousObject.Select(x => x.Value.ToString().Contains("margin")).FirstOrDefault()) { table.MergeAttributes(anonymousObject); } else { anonymousObject.Add("style", "margin: 10px 0px"); } } else if (htmlAttributes != null) { table.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(new { style = "margin: 10px 0px; form-group" })); } return(MvcHtmlString.Create(table.ToString())); }
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())); }
private static MvcHtmlString CKEditorHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, IDictionary <string, object> rowsAndColumns, IDictionary <string, object> htmlAttributes, string ckEditorConfigOptions) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException("string parameter is null or empty", "name"); } TagBuilder textAreaBuilder = new TagBuilder("textarea"); textAreaBuilder.GenerateId(fullName); textAreaBuilder.MergeAttributes(htmlAttributes, true); textAreaBuilder.MergeAttribute("name", fullName, true); string style = ""; if (textAreaBuilder.Attributes.ContainsKey("style")) { style = textAreaBuilder.Attributes["style"]; } if (string.IsNullOrWhiteSpace(style)) { style = ""; } style += string.Format("height:{0}em; width:{1}em;", rowsAndColumns["rows"], rowsAndColumns["cols"]); textAreaBuilder.MergeAttribute("style", style, true); // If there are any errors for a named field, we add the CSS attribute. ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0) { textAreaBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } textAreaBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name)); string value; if (modelState != null && modelState.Value != null) { value = modelState.Value.AttemptedValue; } else if (modelMetadata.Model != null) { value = modelMetadata.Model.ToString(); } else { value = String.Empty; } // The first newline is always trimmed when a TextArea is rendered, so we add an extra one // in case the value being rendered is something like "\r\nHello". textAreaBuilder.SetInnerText(Environment.NewLine + value); TagBuilder scriptBuilder = new TagBuilder("script"); scriptBuilder.MergeAttribute("type", "text/javascript"); if (string.IsNullOrEmpty(ckEditorConfigOptions)) { ckEditorConfigOptions = string.Format("{{ width:'{0}em', height:'{1}em', CKEDITOR.config.allowedContent : true }}", rowsAndColumns["cols"], rowsAndColumns["rows"]); } if (!ckEditorConfigOptions.Trim().StartsWith("{")) { ckEditorConfigOptions = "{" + ckEditorConfigOptions; } if (!ckEditorConfigOptions.Trim().EndsWith("}")) { ckEditorConfigOptions += "}"; } scriptBuilder.InnerHtml = string.Format(" $('#{0}').ckeditor({1}).addClass('{2}'); ", fullName, ckEditorConfigOptions, CK_Ed_Class ); return(MvcHtmlString.Create(textAreaBuilder.ToString() + "\n" + scriptBuilder.ToString())); }