internal static HtmlContentBuilder Numbers <T>(HtmlContentBuilder content, IPaginated <T> paginated, Func <int, string> generatePageUrl, PaginatedOptions options) { if (options.MaximumPageNumbersToDisplay != 8) { paginated.SetPages(options.MaximumPageNumbersToDisplay); } paginated .Pages .ToList() .ForEach(x => { var tagLink = TagLink((paginated.PageNumber != x) ? generatePageUrl(x) : "#", x.ToString(), options.CssClassAnchor); content.AppendHtml(tagLink, (paginated.PageNumber == x) ? options.CssClassLiActive + " " + options.CssClassLi : options.CssClassLi); }); return(content); }
private IHtmlContent GenerateBodyRows(IEnumerable items, ModelMetadata[] props) { var builder = new HtmlContentBuilder(); foreach (var item in items) { builder.AppendHtml("<tr>"); foreach (var prop in props) { // todo: use HtmlHelper.DisplpayFor var value = prop.PropertyGetter(item); builder.AppendFormat("<td>{0}</td>", value); } builder.AppendHtml("</tr>"); } return(builder); }
private HtmlContentBuilder GenerateSpan(HtmlContentBuilder html) { int lastIndex = 0; foreach (var i in PagingContext.PageLinks.GetSpanLinks()) { if (i - lastIndex > 1) { html.AppendHtml($"<a class=\"disabled {SpacerStyle}\">{SpacerText}</>"); } lastIndex = i; var style = (PagingContext.PageIndex == i) ? $" disabled {ActiveStyle}" : DefaultStyle; var anchor = Anchor(i.ToString(), i.ToString(), false, style); html.AppendHtml(anchor); } return(html); }
public static IHtmlContent SortableHeaderFor <TModel, TValue>(this IHtmlHelper <PagingList <TModel> > html, Expression <Func <TModel, TValue> > expression, string sortColumn) where TModel : class { var bldr = new HtmlContentBuilder(); bldr.AppendHtml(html.ActionLink(html.DisplayNameForInnerType(expression), html.ViewData.Model.Action, html.ViewData.Model.GetRouteValueForSort(sortColumn))); IPagingList pagingList = html.ViewData.Model; if (pagingList.SortExpression == sortColumn) { bldr.AppendHtml(PagingOptions.Current.HtmlIndicatorDown); } else if (pagingList.SortExpression == "-" + sortColumn) { bldr.AppendHtml(PagingOptions.Current.HtmlIndicatorUp); } return(bldr); }
public static IHtmlContent UseDnsPrefetch(this RazorPage page) { var serviceLocation = page.Context.RequestServices.GetService <ServiceLocation>(); var builder = new HtmlContentBuilder(); string[] domains = { serviceLocation.API, serviceLocation.OSS, serviceLocation.CDN, serviceLocation.Account }; foreach (var domain in domains) { builder.AppendHtmlLine($@"<link rel='dns-prefetch' href='{domain}'>"); } return(builder); }
public static IHtmlContent DisplayFieldValue(this IHtmlHelper html, FormField field) { HtmlContentBuilder htmlContentBuilder = new HtmlContentBuilder(); if ((field.Name == "Checkbox" || field.Name == "Radio" || field.Name == "Dropdown") && field.FieldOptions != null) { htmlContentBuilder.AppendHtml(string.Join("<br/>", field.FieldOptions.Where(m => m.Selected ?? false).Select(m => m.DisplayText))); } else if (field.Name == "Address" && field.Value.IsNotNullAndWhiteSpace()) { htmlContentBuilder.Append(string.Join(" ", JsonConvert.DeserializeObject <string[]>(field.Value))); } else { htmlContentBuilder.Append(field.Value); } return(htmlContentBuilder); }
public static IHtmlContent BuildBreadcrumbNavigation(this IHtmlHelper helper) { string controllerName = helper.ViewContext.RouteData.Values["controller"].ToString(); string actionName = helper.ViewContext.RouteData.Values["action"].ToString(); var breadcrumb = new HtmlContentBuilder() .AppendHtml(helper.ActionLink("Home", "Index", "Home", null, new { @class = "breadcrumb" })) .AppendHtml(helper.ActionLink(Titleize(controllerName), "Index", controllerName, null, new { @class = "breadcrumb" })); if (helper.ViewContext.RouteData.Values["action"].ToString() != "Index") { breadcrumb.AppendHtml(helper.ActionLink(Titleize(actionName), actionName, controllerName, null, new { @class = "breadcrumb" })); } return(breadcrumb.AppendHtml("")); }
public void Handle(object entity, EventArg e) { if (_applicationSettingService.Get("Animation_Widget_FadeInUp", "false") == "true") { CMSApplicationContext applicationContext = _applicationContextAccessor.Current; HtmlContentBuilder styleBuilder = new HtmlContentBuilder(); HtmlContentBuilder scriptBuilder = new HtmlContentBuilder(); #if DEBUG styleBuilder.AppendHtml("<link type=\"text/css\" async rel=\"stylesheet\" href=\"/Plugins/ZKEACMS.Animation/Content/animate.css\" />"); scriptBuilder.AppendHtml("<script type=\"text/javascript\" src=\"/Plugins/ZKEACMS.Animation/Scripts/animate.js\"></script>"); #else styleBuilder.AppendHtml("<link type=\"text/css\" async rel=\"stylesheet\" href=\"/Plugins/ZKEACMS.Animation/Content/animate.min.css\" />"); scriptBuilder.AppendHtml("<script type=\"text/javascript\" src=\"/Plugins/ZKEACMS.Animation/Scripts/animate.min.js\" ></script>"); #endif applicationContext.HeaderPart.Add(styleBuilder); applicationContext.FooterPart.Add(scriptBuilder); } }
public IHtmlContent Zone(dynamic Display, dynamic Shape) { var htmlContents = new List <IHtmlContent>(); foreach (var item in Shape) { htmlContents.Add(Display(item)); } var htmlContentBuilder = new HtmlContentBuilder(); foreach (var htmlContent in htmlContents) { htmlContentBuilder.AppendHtml(htmlContent); } return(htmlContentBuilder); }
public static IHtmlContent UseAiurDashboardCss(this RazorPage page, bool includeCore = true) { var serviceLocation = page.Context.RequestServices.GetService <ServiceLocation>(); var builder = new HtmlContentBuilder() .AppendHtml($"<meta name=\"theme-color\" content=\"#0082c9\">"); if (includeCore) { return(builder .AppendStyleSheet($"{serviceLocation.UI}/dist/AiurCore.min.css") .AppendStyleSheet($"{serviceLocation.UI}/dist/AiurDashboard.min.css")); } else { return(builder .AppendStyleSheet($"{serviceLocation.UI}/dist/AiurDashboard.min.css")); } }
public static IHtmlContent ReCaptchaV3(string siteKey, string action, string language, string callBack) { var content = new HtmlContentBuilder(); content.AppendHtml(@"<input id=""g-recaptcha-response"" name=""g-recaptcha-response"" type=""hidden"" value="""" />"); content.AppendFormat(@"<script src=""https://www.google.com/recaptcha/api.js?render={0}&hl={1}""></script>", siteKey, language); content.AppendHtml("<script>"); content.AppendHtml("function updateReCaptcha() {"); content.AppendFormat("grecaptcha.execute('{0}', {{action: '{1}'}}).then(function(token){{", siteKey, action); content.AppendHtml("document.getElementById('g-recaptcha-response').value = token;"); content.AppendHtml("});"); content.AppendHtml("}"); content.AppendHtml("grecaptcha.ready(function() {setInterval(updateReCaptcha, 100000); updateReCaptcha()});"); content.AppendHtml("</script>"); content.AppendLine(); return(content); }
public override void Process(TagHelperContext tagHelperContext, TagHelperOutput output) { switch (Type) { case ResourceType.Meta: _resourceManager.RenderMeta(output.Content); break; case ResourceType.HeadLink: _resourceManager.RenderHeadLink(output.Content); break; case ResourceType.Stylesheet: _resourceManager.RenderStylesheet(output.Content); break; case ResourceType.HeadScript: _resourceManager.RenderHeadScript(output.Content); break; case ResourceType.FootScript: _resourceManager.RenderFootScript(output.Content); break; case ResourceType.Header: var htmlBuilder = new HtmlContentBuilder(); _resourceManager.RenderMeta(output.Content); _resourceManager.RenderHeadLink(output.Content); _resourceManager.RenderStylesheet(output.Content); _resourceManager.RenderHeadScript(output.Content); break; case ResourceType.Footer: _resourceManager.RenderFootScript(output.Content); break; default: break; } output.TagName = null; }
private static IHtmlContent CreateLookupValues(IHtmlHelper html, MvcLookup lookup, String name, Object?value) { IDictionary <String, Object> attributes = new Dictionary <String, Object> { ["class"] = "mvc-lookup-value", ["autocomplete"] = "off" }; TagBuilder container = new TagBuilder("div"); container.AddCssClass("mvc-lookup-values"); container.Attributes["data-for"] = name; if (lookup.Multi) { IEnumerable <Object>?values = (value as IEnumerable)?.Cast <Object>(); if (values == null) { return(container); } IHtmlContentBuilder inputs = new HtmlContentBuilder(); foreach (Object val in values) { TagBuilder input = new TagBuilder("input"); input.Attributes["value"] = html.FormatValue(val, null); input.TagRenderMode = TagRenderMode.SelfClosing; input.Attributes["type"] = "hidden"; input.MergeAttributes(attributes); input.Attributes["name"] = name; inputs.AppendHtml(input); } container.InnerHtml.AppendHtml(inputs); } else { container.InnerHtml.AppendHtml(html.Hidden(name, value, attributes)); } return(container); }
// this is old public static string GetFormattedValue(ModelExplorer explorer, DataTypeAttribute dta, bool renderHtml) { HtmlContentBuilder content = new HtmlContentBuilder(); if (explorer.Model == null) { return(string.Empty); } var value = explorer.Model.ToString(); content.SetContent(value); if (dta == null) { return(value); } //TODO: Implement DataTypes as and when these are required value = dta.DataType switch { DataType.Custom => value, DataType.DateTime => FormatDateTime(explorer, dta, value), DataType.Date => FormatDateTime(explorer, dta, value), DataType.Time => FormatDateTime(explorer, dta, value), DataType.Duration => value, DataType.PhoneNumber => value, DataType.Currency => value, DataType.Text => value, DataType.Html => value, DataType.MultilineText => value, DataType.EmailAddress => value, DataType.Password => value, DataType.Url => value, DataType.ImageUrl => value, DataType.CreditCard => value, DataType.PostalCode => value, DataType.Upload => value, _ => value }; content.SetContent(value); return(value); }
public static HtmlContentBuilder GenerateRadioValueList(ViewContext viewContext, ModelExplorer modelExplorer, string expression, bool inline, IEnumerable <SelectListItem> selectList, ICollection <string> currentValues, object divHtmlAttributes, object inputHtmlAttributes, object labelHtmlAttributes) { selectList = GetSelectListItems(viewContext, modelExplorer, expression, selectList, currentValues); var listItemBuilder = new HtmlContentBuilder(); foreach (var item in selectList) { var selected = item.Selected; if (currentValues != null) { var value = item.Value ?? item.Text; selected = currentValues.Contains(value); } listItemBuilder.AppendHtml(GenerateRadioValue(viewContext, null, expression, inline, item.Value, item.Text, selected, divHtmlAttributes, inputHtmlAttributes, labelHtmlAttributes)); } return(listItemBuilder); }
public static IHtmlContent SortableHeaderFor <TModel, TValue>(this IHtmlHelper <PagingList <TModel> > html, Expression <Func <TModel, TValue> > expression, string sortColumn, IPagingList pagingList) where TModel : class { var bldr = new HtmlContentBuilder(); bldr.AppendHtml(SortableHeaderFor(html, expression, sortColumn)); if (pagingList.SortExpression == sortColumn) { bldr.AppendHtml(PagingOptions.Current.HtmlIndicatorDown); } else { if (pagingList.SortExpression == "-" + sortColumn) { bldr.AppendHtml(PagingOptions.Current.HtmlIndicatorUp); } } return(bldr); }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (string.IsNullOrEmpty(this.Message)) { return; } var content = new HtmlContentBuilder(); content.AppendHtmlLine($"<div class=\"alert alert-{this.Type}\">"); content.AppendHtmlLine(" <button type=\"button\" class=\"close\" data-dismiss=\"alert\">"); content.AppendHtmlLine(" <span aria-hidden=\"true\">×</span>"); content.AppendHtmlLine(" <span class=\"sr-only\">Close</span>"); content.AppendHtmlLine(" </button>"); content.AppendHtmlLine(this.Message); content.AppendHtmlLine("</div>"); output.Content.SetHtmlContent(content); }
public static IHtmlContent RAStaticTable <TModel, TTableRowItem>(this IHtmlHelper <TModel> htmlHelper, IList <TTableRowItem> dynamicTableRowItems, string ajaxCreateRowUrl, string AddRowLinkText) where TTableRowItem : RATableRowItemBase { var content = new HtmlContentBuilder(); content.AppendHtml("<table class=\"ra-statictable\">"); content.AppendHtml("<tbody class=\"ra-statictable-body\">"); foreach (var rowItem in dynamicTableRowItems) { content.AppendHtml(htmlHelper.EditorFor(x => rowItem)); } content.AppendHtml("</tbody>"); content.AppendHtml("</table>"); return(content); }
async Task <IHtmlContent> Build() { EnsureViewHelper(); HtmlContentBuilder builder = null; if (this.Model is IEnumerable <IView> ) { builder = new HtmlContentBuilder(); foreach (var view in Model) { try { var result = await _viewDisplayHelper.DisplayAsync(view); builder.AppendHtml(result); } catch { throw; } } } else { if (this.Model is IView) { builder = new HtmlContentBuilder(); try { var result = await _viewDisplayHelper.DisplayAsync(this.Model); builder.AppendHtml(result); } catch { throw; } } } return(builder); }
public void CopyTo_CopiesToBuilder(TagHelperOutput output, string expected) { // Arrange var attributeCount = output.Attributes.Count; var writer = new StringWriter(); var testEncoder = new HtmlTestEncoder(); var buffer = new HtmlContentBuilder(); // Act ((IHtmlContentContainer)output).CopyTo(buffer); // Assert buffer.WriteTo(writer, testEncoder); Assert.Equal(attributeCount, output.Attributes.Count); Assert.Equal(expected, writer.ToString(), StringComparer.Ordinal); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { // Client & server var utcDateTime = Utc ?? DateTimeOffset.UtcNow; var user = await _contextFacade.GetAuthenticatedUserAsync(); // Get local date time, only apply client offset if user is authenticated var localDateTime = await _localDateTimeProvider.GetLocalDateTimeAsync(new LocalDateTimeOptions() { UtcDateTime = utcDateTime, ServerTimeZone = _settings?.TimeZone, ClientTimeZone = user?.TimeZone, ApplyClientTimeZoneOffset = user != null }); // Date format var dateTimeFormat = GetDefaultDateTimeFormat(); // We always need the full regular date for the title attribute (not the pretty date) var formattedDateTime = localDateTime.DateTime.ToString(dateTimeFormat); // Build output var builder = new HtmlContentBuilder(); output.TagName = "span"; output.TagMode = TagMode.StartTagAndEndTag; if (!output.Attributes.ContainsName("title")) { output.Attributes.Add("title", formattedDateTime); } if (!output.Attributes.ContainsName("data-toggle")) { output.Attributes.Add("data-toggle", "tooltip"); } output.Content.SetHtmlContent(Pretty ? builder.AppendHtml(utcDateTime.DateTime.ToPrettyDate(dateTimeFormat)) : builder.AppendHtml(formattedDateTime)); }
public static IHtmlContent RADynamicTable <TModel, TTableRowItem>( this IHtmlHelper <TModel> htmlHelper, Expression <Func <TModel, IList <TTableRowItem> > > tableRowItemsExpression, string rowViewName, string ajaxAddRowUrl, string addRowLinkText, string addButtonClass = "ra-btn-theme", string tHeadInnerHtml = null) where TTableRowItem : IDynamicTableRowItem { var content = new HtmlContentBuilder(); string tableId = Guid.NewGuid().ToString().Replace("-", ""); content.AppendFormat("<table id=\"{0}\" class=\"ra-dynamictable\">", tableId); if (!String.IsNullOrEmpty(tHeadInnerHtml)) { content.AppendHtml("<thead>" + tHeadInnerHtml + "</thead>"); } content.AppendHtml("<tbody class=\"ra-dynamictable-body\">"); var htmlFieldPrefix = htmlHelper.GetExpressionText(tableRowItemsExpression); var modelExplorer = htmlHelper.GetModelExplorer(tableRowItemsExpression); foreach (var rowItem in (IList <TTableRowItem>)modelExplorer.Model) { rowItem.HtmlFieldPrefix = htmlFieldPrefix; content.AppendHtml(htmlHelper.Partial(rowViewName, rowItem)); //htmlHelper.EditorFor(x => rowItem)); } var completeAjaxAddRowUrl = ajaxAddRowUrl += "&htmlFieldPrefix=" + htmlFieldPrefix; content.AppendHtml("</tbody>"); content.AppendHtml("</table>"); content.AppendHtml("<div>"); content.AppendHtml(htmlHelper.RAButton("<i class='fas fa-plus'></i> " + addRowLinkText, string.Format("raAddDynamicTableRow('{0}', '{1}');", tableId, completeAjaxAddRowUrl), buttonClass: $"{addButtonClass} ra-btn-xs")); content.AppendHtml("</button>"); content.AppendHtml("</div>"); return(content); }
static void BuildMenuTree(TreeViewNode node, List <TreeViewNode> sources, HtmlContentBuilder htmlBuilder, bool showCheckbox = true, string actionsHtml = "") { var children = sources.Where(x => x.ParentId != null && node.Id != null && x.ParentId.ToString() == node.Id.ToString()); htmlBuilder.AppendHtmlLine($"<li class='list-group-item {(children.Any() ? "" : "pl-4")} border-top'>"); if (children.Any()) { htmlBuilder.AppendHtmlLine("<a class='collapse-icon' href='#'><i class='fa fa-fw fa-plus'></i></a>"); } if (showCheckbox) { htmlBuilder.AppendHtmlLine("<div class='custom-control custom-checkbox d-inline'>"); htmlBuilder.AppendHtmlLine($"<input type='checkbox' class='custom-control-input' id='node_{node.Id}' name='idArray' value='{node.Id}'>"); htmlBuilder.AppendHtmlLine($"<label class='custom-control-label' for='node_{node.Id}'> {node.Name}</label>"); htmlBuilder.AppendHtmlLine("</div>"); } // actions //if ( editUrl != "" ) { // htmlBuilder.AppendHtmlLine($"<a href='#' class='ml-1' data-toggle='modal' data-target='#modal_dialog_layout' data-modal-title='Edit' data-modal-url='{editUrl}/{node.Id}' data-modal-size='lg'><i class='fa fa-fw fa-edit'></i></a>"); //} //if ( removeUrl != "" ) { // htmlBuilder.AppendHtmlLine($"<a href='#' class='text-danger' data-toggle='modal' data-target='#modal_confirm_layout' data-url='{removeUrl}?handler=Remove&idArray={node.Id}' data-alert-panel='#alert_panel' data-update-panel='#menuContainer'><i class='fa fa-fw fa-remove'></i></a>"); //} htmlBuilder.AppendHtmlLine(actionsHtml.Replace("#=Id #", node.Id == null ? "" : node.Id.ToString())); if (children.Any()) { htmlBuilder.AppendHtmlLine($"<ul class='list-group list-group-flush tree-view-custom d-none mt-1 pt-2' id='collapse_{node.Id}'>"); foreach (var child in children) { BuildMenuTree(child, sources, htmlBuilder, showCheckbox, actionsHtml); } htmlBuilder.AppendHtmlLine("</ul>"); } htmlBuilder.AppendHtmlLine("</li>"); }
public static IHtmlContent BuildBreadcrumbNavigation(this IHtmlHelper helper) { string controllerName = helper.ViewContext.RouteData.Values["controller"].ToString(); string actionName = helper.ViewContext.RouteData.Values["action"].ToString(); var breadcrumb = new HtmlContentBuilder() .AppendHtml("<li class='list-inline-item'>") .AppendHtml(helper.ActionLink(controllerName.Titleize(), "Index", controllerName)) .AppendHtml("</li>"); if (helper.ViewContext.RouteData.Values["action"].ToString() != "Index") { breadcrumb.AppendHtml("<li class='list-inline-item' style=' color: #808080'>") .AppendHtml(helper.ActionLink(actionName.Titleize(), actionName, controllerName)) .AppendHtml("</li>"); } return(breadcrumb); }
public static IHtmlContent Navigation(this IHtmlHelper htmlHelper, List <NavigationEntry> navigationEntries) { var html = new HtmlContentBuilder(); foreach (var n in navigationEntries) { if (n.Children.Count > 0) { var li = ActionLinkTopLevelChildren(htmlHelper, n.LinkText, n.ActionName, n.ControllerName, n.FaIncon, n.Children); html.AppendHtml(Common.GetString(li)); } else { var li = ActionLinkTopLevel(htmlHelper, n.LinkText, n.ActionName, n.ControllerName, n.FaIncon); html.AppendHtml(Common.GetString(li)); } } return(html); }
public IHtmlContent RenderMeta() { var htmlBuilder = new HtmlContentBuilder(); var first = true; foreach (var meta in this.GetRegisteredMetas()) { if (!first) { htmlBuilder.AppendHtml(Environment.NewLine); } first = false; htmlBuilder.AppendHtml(meta.GetTag()); } return(htmlBuilder); }
public IHtmlContent RenderHeadLink() { var htmlBuilder = new HtmlContentBuilder(); var first = true; foreach (var link in this.GetRegisteredLinks()) { if (!first) { htmlBuilder.AppendHtml(Environment.NewLine); } first = false; htmlBuilder.AppendHtml(link.GetTag()); } return(htmlBuilder); }
public static IHtmlContent RenderPartialSectionStyles(this IHtmlHelper htmlHelper) { var partialSectionStyles = htmlHelper.ViewContext.HttpContext.Items.Keys .Where(k => Regex.IsMatch( k.ToString(), "^" + _partialViewStylesItemPrefix + "([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$")); var contentBuilder = new HtmlContentBuilder(); foreach (var key in partialSectionStyles) { var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func <object, HelperResult>; if (template != null) { var writer = new System.IO.StringWriter(); template(null).WriteTo(writer, HtmlEncoder.Default); contentBuilder.AppendHtml(writer.ToString()); } } return(contentBuilder); }
public static IHtmlContent ImageBanner(this IHtmlHelper htmlhelper, string Imagesource, string altTxt, string width, string height) { var divStart = "<div style = \"border: 2px solid gray; padding:10px; width: fit-content; margin - left: auto; margin - right: auto; \" >"; var divEnd = "</div>"; var ImageTag = new TagBuilder("img"); // src Specifies the path to the image ImageTag.MergeAttribute("src", Imagesource); // alt - Specifies an alternate text for the image, if the image for some reason cannot be displayed ImageTag.MergeAttribute("alt", altTxt); ImageTag.MergeAttribute("width", width); ImageTag.MergeAttribute("height", height); var content = new HtmlContentBuilder() .AppendHtml(divStart) .AppendHtml(ImageTag) .AppendHtml(divEnd); return(content); }
protected override async Task ProcessCoreAsync(TagHelperContext context, TagHelperOutput output) { await output.LoadAndSetChildContentAsync(); output.TagName = "div"; output.AppendCssClass("modal"); if (Fade) { output.AppendCssClass("fade"); } if (CenterContent) { output.AppendCssClass("modal-box"); } output.MergeAttribute("role", "dialog"); output.MergeAttribute("tabindex", -1); output.MergeAttribute("aria-hidden", "true"); output.MergeAttribute("aria-labelledby", Id + "Label"); output.MergeAttribute("data-keyboard", CloseOnEscapePress.ToString().ToLower()); output.MergeAttribute("data-show", Show.ToString().ToLower()); output.MergeAttribute("data-focus", Focus.ToString().ToLower()); output.MergeAttribute("data-backdrop", Backdrop ? (CloseOnBackdropClick ? "true" : "static") : "false"); // .modal-dialog BuildDialog(output); // .modal-content BuildContent(output); if (RenderAtPageEnd && !ViewContext.HttpContext.Request.IsAjaxRequest()) { // Move output Html to new builder var builder = new HtmlContentBuilder(); ((IHtmlContentContainer)output).MoveTo(builder); _widgetProvider.RegisterHtml("end", builder); output.SuppressOutput(); } }
public static IHtmlContent CollectionTemplate(IHtmlHelper htmlHelper) { var viewData = htmlHelper.ViewData; var model = viewData.Model; if (model == null) { return HtmlString.Empty; } var collection = model as IEnumerable; if (collection == null) { // Only way we could reach here is if user passed templateName: "Collection" to an Editor() overload. throw new InvalidOperationException(Resources.FormatTemplates_TypeMustImplementIEnumerable( "Collection", model.GetType().FullName, typeof(IEnumerable).FullName)); } var elementMetadata = htmlHelper.ViewData.ModelMetadata.ElementMetadata; Debug.Assert(elementMetadata != null); var typeInCollectionIsNullableValueType = elementMetadata.IsNullableValueType; var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices; var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>(); // Use typeof(string) instead of typeof(object) for IEnumerable collections. Neither type is Nullable<T>. if (elementMetadata.ModelType == typeof(object)) { elementMetadata = metadataProvider.GetMetadataForType(typeof(string)); } var oldPrefix = viewData.TemplateInfo.HtmlFieldPrefix; try { viewData.TemplateInfo.HtmlFieldPrefix = string.Empty; var fieldNameBase = oldPrefix; var result = new HtmlContentBuilder(); var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>(); var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>(); var index = 0; foreach (var item in collection) { var itemMetadata = elementMetadata; if (item != null && !typeInCollectionIsNullableValueType) { itemMetadata = metadataProvider.GetMetadataForType(item.GetType()); } var modelExplorer = new ModelExplorer( metadataProvider, container: htmlHelper.ViewData.ModelExplorer, metadata: itemMetadata, model: item); var fieldName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", fieldNameBase, index++); var templateBuilder = new TemplateBuilder( viewEngine, viewBufferScope, htmlHelper.ViewContext, htmlHelper.ViewData, modelExplorer, htmlFieldName: fieldName, templateName: null, readOnly: false, additionalViewData: null); result.AppendHtml(templateBuilder.Build()); } return result; } finally { viewData.TemplateInfo.HtmlFieldPrefix = oldPrefix; } }
public static IHtmlContent ObjectTemplate(IHtmlHelper htmlHelper) { var viewData = htmlHelper.ViewData; var templateInfo = viewData.TemplateInfo; var modelExplorer = viewData.ModelExplorer; if (templateInfo.TemplateDepth > 1) { if (modelExplorer.Model == null) { return new HtmlString(modelExplorer.Metadata.NullDisplayText); } var text = modelExplorer.GetSimpleDisplayText(); if (modelExplorer.Metadata.HtmlEncode) { return new StringHtmlContent(text); } return new HtmlString(text); } var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices; var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>(); var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>(); var content = new HtmlContentBuilder(); foreach (var propertyExplorer in modelExplorer.Properties) { var propertyMetadata = propertyExplorer.Metadata; if (!ShouldShow(propertyExplorer, templateInfo)) { continue; } var templateBuilder = new TemplateBuilder( viewEngine, viewBufferScope, htmlHelper.ViewContext, htmlHelper.ViewData, propertyExplorer, htmlFieldName: propertyMetadata.PropertyName, templateName: null, readOnly: false, additionalViewData: null); var templateBuilderResult = templateBuilder.Build(); if (!propertyMetadata.HideSurroundingHtml) { var label = htmlHelper.Label(propertyMetadata.PropertyName, labelText: null, htmlAttributes: null); if (!string.IsNullOrEmpty(label.ToString())) { var labelTag = new TagBuilder("div"); labelTag.AddCssClass("editor-label"); labelTag.InnerHtml.SetContent(label); content.AppendLine(labelTag); } var valueDivTag = new TagBuilder("div"); valueDivTag.AddCssClass("editor-field"); valueDivTag.InnerHtml.AppendHtml(templateBuilderResult); valueDivTag.InnerHtml.AppendHtml(" "); valueDivTag.InnerHtml.AppendHtml(htmlHelper.ValidationMessage( propertyMetadata.PropertyName, message: null, htmlAttributes: null, tag: null)); content.AppendLine(valueDivTag); } else { content.AppendHtml(templateBuilderResult); } } return content; }
public static IHtmlContent HiddenInputTemplate(IHtmlHelper htmlHelper) { var viewData = htmlHelper.ViewData; var model = viewData.Model; var result = new HtmlContentBuilder(); if (!viewData.ModelMetadata.HideSurroundingHtml) { result.AppendHtml(DefaultDisplayTemplates.StringTemplate(htmlHelper)); } // Special-case opaque values and arbitrary binary data. var modelAsByteArray = model as byte[]; if (modelAsByteArray != null) { model = Convert.ToBase64String(modelAsByteArray); } var htmlAttributesObject = viewData[HtmlAttributeKey]; var hiddenResult = htmlHelper.Hidden(expression: null, value: model, htmlAttributes: htmlAttributesObject); result.AppendHtml(hiddenResult); return result; }