public static IHtmlContent AutoCompleteFor <TModel, TProperty>(this IHtmlHelper <TModel> html, Expression <Func <TModel, TProperty> > expression, MvcLookup model, Object htmlAttributes = null) { String name = ExpressionHelper.GetExpressionText(expression); HtmlContentBuilder autocomplete = new HtmlContentBuilder(); autocomplete.AppendHtml(FormAutoComplete(html, model, name, htmlAttributes)); autocomplete.AppendHtml(FormHiddenInputFor(html, expression)); return(autocomplete); }
public static IHtmlContent PEPagerLinkWithText(this IHtmlHelper htmlHelper, string linkText, string actionName, string fieldName, PagingModel paging, object routeValues = null) { var retvalue = new HtmlContentBuilder(); var linkRd = routeValues != null ? new RouteValueDictionary(routeValues) : new RouteValueDictionary(); linkRd.Add("sortField", fieldName); linkRd.Add("sortAscending", paging.SortField == fieldName ? !paging.SortAscending : true); retvalue.AppendHtml(htmlHelper.PEPagerLink(linkText, actionName, 1, paging.Count, linkRd)); retvalue.AppendHtml(paging.SortField == fieldName ? paging.SortAscending ? "[A]" : "[D]" : string.Empty); return(retvalue); }
private static IHtmlContent PEPager(this IHtmlHelper htmlHelper, int start, int count, int total, RouteValueDictionary routeValues, object htmlAttributes, string action) { HtmlContentBuilder retvalue = new HtmlContentBuilder(); if (start > 1) { RouteValueDictionary linkRd = CopyRVD(routeValues); linkRd.Add("start", 1); linkRd.Add("count", count); retvalue.AppendHtml(htmlHelper.ActionLink("[Start]", action, linkRd, new RouteValueDictionary(htmlAttributes))); retvalue.AppendHtml(" "); linkRd = CopyRVD(routeValues); linkRd.Add("start", start - count); linkRd.Add("count", count); retvalue.AppendHtml(htmlHelper.ActionLink("[Prev]", action, linkRd, new RouteValueDictionary(htmlAttributes))); } else { if (total > count) { retvalue.AppendHtml("[Start] [Prev]"); } } if (total > count) { retvalue.AppendHtml(string.Format(" <span>{0} to {1} of {2}</span> ", start, total < start + count ? total : start + count - 1, total)); } else { retvalue.AppendHtml(string.Format(" <span>{0} of {0} ", total)); } if (total > (start + count) - 1) { RouteValueDictionary linkRd = CopyRVD(routeValues); linkRd.Add("start", start + count); linkRd.Add("count", count); retvalue.AppendHtml(htmlHelper.ActionLink("[Next]", action, linkRd, new RouteValueDictionary(htmlAttributes))); retvalue.AppendHtml(" "); linkRd = CopyRVD(routeValues); linkRd.Add("start", (total - (total % count)) + 1); linkRd.Add("count", count); retvalue.AppendHtml(htmlHelper.ActionLink("[End]", action, linkRd, new RouteValueDictionary(htmlAttributes))); } else { if (total > count) { retvalue.AppendHtml("[Next] [End]"); } } return(retvalue); }
public override void Process(TagHelperContext context, TagHelperOutput output) { var builder = new HtmlContentBuilder(); builder.AppendHtml(Anchor("Previous", (PagingContext.PageIndex - 1).ToString(), !PagingContext.HasPrevious, DefaultStyle)); builder = GenerateSpan(builder); builder.AppendHtml(Anchor("Next", (PagingContext.PageIndex + 1).ToString(), !PagingContext.HasNext, DefaultStyle)); output.TagName = "div"; output.Content.SetHtmlContent(builder); }
private static string RenderRow(IHtmlHelper helper, DataColumn[] columns, object item, DataGridOptions option) { var builder = new HtmlContentBuilder(); var idx = ""; var idclass = ""; if (option.RowFormatClass != null && !option.RowFormatFunction.IsEmpty()) { var obj = Activator.CreateInstance(option.RowFormatClass); var a = option.RowFormatClass.GetMethod(option.RowFormatFunction); var sonuc = (string)a.Invoke(obj, new dynamic[1] { item }); idclass = $"class='{sonuc}'"; } builder.AppendHtml($"<tr {idx} {idclass}>"); if (string.IsNullOrWhiteSpace(_exportMode)) { builder.AppendHtml(RenderRowButtons(helper, item, option)); foreach (var column in columns.Where(d => d.Visible && d.DataColumnType == DataColumnTypes.CommandColumn)) { var val = Digger.GetObjectValue(item, column.FieldName); if (val is List <DataGridCommand> ) { builder.AppendHtml(RenderRowButtons(val as List <DataGridCommand>)); } } } foreach (var field in columns.Where(d => d.Visible && d.DataColumnType != DataColumnTypes.CommandColumn)) { if (field.Width > 0) { builder.AppendHtml($"<td width='{field.Width}'>"); } else { builder.AppendHtml("<td>"); } if (string.IsNullOrWhiteSpace(field.ObjectValueFunction) || field.ObjectValueConverter == null) { builder.AppendHtml(ValueConverter.GetValue(helper, item, field)); } else { var type = field.ObjectValueConverter; var obj = Activator.CreateInstance(type); var a = type.GetMethod(field.ObjectValueFunction); var sonuc = (string)a.Invoke(obj, new object[2] { helper, item }); builder.AppendHtml(sonuc); } builder.AppendHtml("</td>"); } builder.AppendHtml("</tr>"); return(builder.GetString()); }
public static IHtmlContent DisplayCharacterName <TModel>(this IHtmlHelper <TModel> html, string val) { var ret = new HtmlContentBuilder(); var index = val.IndexOf('('); if (index == -1) { ret.AppendHtml(HttpUtility.HtmlEncode(val)); } else { ret.AppendHtml(@"<span style=""display:inline-block"">"); ret.AppendHtml(HttpUtility.HtmlEncode(val[0..index]));
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 || "-" + pagingList.SortExpression == sortColumn || pagingList.SortExpression == "-" + sortColumn) { bldr.AppendHtml(pagingList.SortExpression.StartsWith("-") ? PagingOptions.Current.HtmlIndicatorUp : PagingOptions.Current.HtmlIndicatorDown); } return(bldr); }
public override IHtmlContent GenerateHtml() { IHtmlContentBuilder contentBuilder = new HtmlContentBuilder(); contentBuilder.AppendHtml("h1"); contentBuilder.AppendHtml("h2"); //contentBuilder.SetContent("This is the content"); StringWriter writer = new StringWriter(); contentBuilder.WriteTo(writer, HtmlEncoder.Default); return(contentBuilder); }
public static IHtmlContent WidgetHeaderLink(this IHtmlHelper htmlHelper, IPSFBase psf, string columnName, string displayName) { var content = new HtmlContentBuilder(); content.AppendHtml("<a href=\"?&SortAscending=" + ((!psf.SortAscending).ToString()) + "&sortBy=" + (columnName) + (psf.Filter) + "\" class=\"bold\">" + displayName); if (psf.SortBy == columnName) { string sortDirection = (psf.SortAscending) ? "asc" : "desc"; content.AppendHtml(" <img src=\"/CustomAssets/images/" + (sortDirection) + ".gif\" height=\"8\" width=\"8\" alt=\"\" class=\"AscDesc\" />"); } content.AppendHtml("</a>"); return(content); }
private IHtmlContent GenerateHeaderRow(ModelMetadata[] props) { var builder = new HtmlContentBuilder(); builder.AppendHtml("<tr>"); foreach (var prop in props) { builder.AppendFormat("<th>{0}</th>", prop.DisplayName); } builder.AppendHtml("</tr>"); return(builder); }
public IHtmlContent GetTag() { if (!string.IsNullOrEmpty(Condition)) { var htmlBuilder = new HtmlContentBuilder(); htmlBuilder.AppendHtml("<!--[if " + Condition + "]>"); htmlBuilder.AppendHtml(_builder); htmlBuilder.AppendHtml("<![endif]-->"); return(htmlBuilder); } return(_builder); }
private IHtmlContent CreateTitleElement() { var content = new HtmlContentBuilder(); var title = new TagBuilder("h6"); title.Attributes.Add("style", "padding-left: 20px"); content.AppendHtml(title.RenderStartTag()); content.Append("Copy from old entity"); content.AppendHtml(title.RenderEndTag()); return(content); }
/// <summary> /// Return file uploader control full item (with caption) initialized with finUploader plugin /// </summary> /// <param name="expression">Lambda expression for the string property to bind file path to</param> /// <param name="controllerName">Upload controller name that contains upload and delete actions</param> /// <param name="allowedExtensions">Allowed extensions to upload</param> /// <param name="fileMaxSize">Maximum file size to upload</param> /// <param name="withValidation">Add Validation message control?</param> /// <param name="spanOf12">Number represents bootstrap column span for the item width</param> /// <param name="onSuccessCallback">Javascript function name to call after upload success</param> /// <param name="onDeleteCallback">Javascript function name to call after deleting afile from the uploader</param> /// <param name="hint">Optional text to add after the caption label as a hint</param> /// <returns>HtmlString for uploader control with caption label</returns> public static IHtmlContent FileUploadFormItemFor <TModel, TProperty>( this IHtmlHelper <TModel> helper, Expression <Func <TModel, TProperty> > expression, string controllerName = "Upload", IEnumerable <string> allowedExtensions = null, int fileMaxSize = 2048, int numberOfFilesToUpload = 1, bool multiple = false, bool withValidation = true, int spanOf12 = 6, string onSuccessCallback = "", string onDeleteCallback = "", string hint = "") { HtmlContentBuilder htmlContentBuilder = new HtmlContentBuilder(); var expresionProvider = helper.ViewContext.HttpContext.RequestServices .GetService(typeof(ModelExpressionProvider)) as ModelExpressionProvider; string name = expresionProvider.GetExpressionText(expression); if (allowedExtensions == null || !allowedExtensions.Any()) { allowedExtensions = allowedExtensionsDeafault; } var col = new ItemsColumnTagBuilder(spanOf12, null); var frmGroup = new FormGroupTagBuilder(); var uploader = helper.FileUploaderFor(expression, controllerName, allowedExtensions, fileMaxSize, numberOfFilesToUpload, multiple, onSuccessCallback, onDeleteCallback); htmlContentBuilder.AppendHtml(col.RenderStartTag()) .AppendHtml(frmGroup.RenderStartTag()) .AppendHtml(helper.LabelFor(expression)); if (!string.IsNullOrEmpty(hint)) { htmlContentBuilder.AppendHtml(new FormItemHintTagBuilder(hint)); } htmlContentBuilder.AppendHtml(uploader); if (withValidation) { htmlContentBuilder.AppendHtml(helper.ValidationMessageFor(expression)); } htmlContentBuilder.AppendHtml(frmGroup.RenderEndTag()) .AppendHtml(col.RenderEndTag()); return(htmlContentBuilder); }
static IHtmlContent RadioInternal(IHtmlHelper htmlHelper, string name, IEnumerable <SelectListItem> items, IDictionary <string, object> cbxHtmlAttributes, IDictionary <string, object> lableHtmlAttributes, IDictionary <string, object> itemGroupAttributes) { if (items.IsNullOrEmpty()) { return(HtmlString.Empty); } string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (string.IsNullOrWhiteSpace(fullName)) { throw new ArgumentException("radio name is null Or empty"); } var radioBuilder = new HtmlContentBuilder(); int i = 0; foreach (SelectListItem item in items) { string cbxId = string.Format("rdo-{0}-{1}", fullName, i.ToString()); //group TagBuilder groupTag = new TagBuilder("span"); groupTag.MergeAttribute("rdo-group-id", cbxId); groupTag.MergeAttributes(itemGroupAttributes); //cbx TagBuilder cbxTag = new TagBuilder("input"); cbxTag.MergeAttribute("rdo-id", cbxId); cbxTag.MergeAttribute("id", cbxId); cbxTag.MergeAttributes(cbxHtmlAttributes); cbxTag.MergeAttribute("type", GetInputTypeName(InputType.Radio)); cbxTag.MergeAttribute("value", item.Value); cbxTag.MergeAttribute("name", fullName); if (item.Selected) { cbxTag.MergeAttribute("checked", "checked"); } //lable TagBuilder labTag = new TagBuilder("label"); labTag.MergeAttributes(lableHtmlAttributes); labTag.MergeAttribute("rdo-lable-id", cbxId); labTag.MergeAttribute("for", cbxId); labTag.InnerHtml.SetContent(item.Text); var groupInnerBuilder = new HtmlContentBuilder(2); groupInnerBuilder.AppendHtml(cbxTag); groupInnerBuilder.AppendHtml(labTag); groupTag.InnerHtml.SetHtmlContent(groupInnerBuilder); radioBuilder.AppendHtml(groupTag); i++; } return(radioBuilder); }
public static IHtmlContent BuildBreadcrumbNavigation(this IHtmlHelper helper) { if (helper.ViewContext.RouteData.Values["controller"].ToString() == "Home") { return(_emptyBuilder); } string controllerName = helper.ViewContext.RouteData.Values["controller"].ToString(); string actionName = helper.ViewContext.RouteData.Values["action"].ToString(); var controllerAlias = ""; if (controllerName == "OperationTypes") { controllerAlias = controllerName.Replace("OperationTypes", "Operation Types"); } else if (controllerName == "LoginLog") { controllerAlias = "Login Times"; } else { controllerAlias = controllerName; } if (!controllerName.Titleize().EndsWith("s")) { controllerAlias = controllerName + "s"; } var breadcrumb = new HtmlContentBuilder() .AppendHtml("<ol class='breadcrumb'><li class='breadcrumb-item'>") .AppendHtml(helper.ActionLink("Home", "Index", "Home")) .AppendHtml("</li><li class='breadcrumb-item'>") .AppendHtml(helper.ActionLink(controllerAlias.Titleize(), "Index", controllerName)) .AppendHtml("</li>"); if (helper.ViewContext.RouteData.Values["action"].ToString() != "Index" && controllerName != "Reports") { breadcrumb.AppendHtml("<li class='breadcrumb-item'>") .AppendHtml(helper.ActionLink(actionName.Titleize().Replace("Operationsreport", "Operations Report"), actionName, controllerName)) .AppendHtml("</li>"); } return(breadcrumb.AppendHtml("</ol>")); }
/// <summary> /// Build the table body tag /// </summary> /// <param name="viewModel"></param> /// <returns></returns> private static IHtmlContent BlogIndexBody(IndexViewModel viewModel) { // Create a content builder just to make the looped items content HtmlContentBuilder itemsBuilder = new HtmlContentBuilder(); // Build the clearfix insert classes from the model templates so we don't have to retrieve them each time String clearFixMedium = $" {viewModel.Templates.Get(BlogViewTemplatePart.Index_Clearfix_Medium).GetString()}"; String clearFixLarge = $" {viewModel.Templates.Get(BlogViewTemplatePart.Index_Clearfix_Large).GetString()}"; // Loop the results and create the row for each result in the itemsBuilder Int32 itemId = 0; // Counter to count the amount of items there are viewModel.Results .ForEach(blogHeader => { // Add the new item Html itemId++; itemsBuilder.AppendHtml(BlogItem(new BlogItem() { Header = (BlogHeader)blogHeader }, (BlogViewModelBase)viewModel)); // Built up template content classes to transpose in the clearfix template should it be needed String clearfixHtml = ""; clearfixHtml += (itemId % viewModel.DisplaySettings.ViewPorts[BlogViewSize.Medium].Columns == 0) ? clearFixMedium : ""; clearfixHtml += (itemId % viewModel.DisplaySettings.ViewPorts[BlogViewSize.Large].Columns == 0) ? clearFixLarge : ""; // Do we have a clearfix to append? if (clearfixHtml != "") { // .. yes we do, append the clearfix with the appropriate template and the class string that was built itemsBuilder.AppendHtml(ContentFill(BlogViewTemplatePart.Index_Clearfix, new List <BlogViewTemplateReplacement>() { new BlogViewTemplateReplacement(BlogViewTemplateField.Index_BlogItem_ClearFix, clearfixHtml, false) }, viewModel)); } } ); // Call the standard content filler function return(ContentFill(BlogViewTemplatePart.Index_Body, new List <BlogViewTemplateReplacement>() { new BlogViewTemplateReplacement(BlogViewTemplateField.Index_Body_Items, itemsBuilder.GetString(), false) }, viewModel)); }
private static IHtmlContent AjaxRenderSearchPageAndPageSizeDiv <T>(IHtmlHelper helper, TargetPager <T> dataList, string divClassName, object routeValues, string updateTarget, string action, string controller) { HtmlContentBuilder pagerHtmlContentBuilder = new HtmlContentBuilder(); string goelementId = updateTarget + "_pageIndexInputId"; string perPageelementId = updateTarget + "_pager_pagesize_selectid"; IHtmlContent ajaxLink = helper.ActionLink("Go", action, controller, routeValues, new { data_ajax = "true", data_ajax_method = "Post", data_ajax_mode = "replace", data_ajax_update = "#" + updateTarget, @class = "go", @onclick = "setJumpPagerLinkWithGo(" + dataList.PageIndex + "," + dataList.PageTotal + "," + goelementId + "," + perPageelementId + ", this)" }); IHtmlContent ajaxLinkHide = helper.ActionLink("Go", action, controller, routeValues, new { data_ajax = "true", data_ajax_method = "Post", data_ajax_mode = "replace", data_ajax_update = "#" + updateTarget, @id = updateTarget + "_perPageHiddenGo", @hidden = "hidden", @onclick = "setJumpPagerLinkWithPerPage(" + dataList.PageIndex + "," + dataList.PageTotal + "," + perPageelementId + ", this )" }); pagerHtmlContentBuilder.AppendHtml(AjaxRenderToPageDiv(dataList, ajaxLink, updateTarget)); pagerHtmlContentBuilder.AppendHtml(AjaxRenderSetSizeDiv(dataList, ajaxLinkHide, updateTarget)); return(pagerHtmlContentBuilder); }
private protected override IHtmlContent GenerateFormGroupContent( TagHelperContext tagHelperContext, FormGroupContext formGroupContext, TagHelperOutput tagHelperOutput, IHtmlContent childContent, out bool haveError) { var contentBuilder = new HtmlContentBuilder(); var label = GenerateLabel(formGroupContext); contentBuilder.AppendHtml(label); var hint = GenerateHint(tagHelperContext, formGroupContext); if (hint != null) { contentBuilder.AppendHtml(hint); } var errorMessage = GenerateErrorMessage(tagHelperContext, formGroupContext); if (errorMessage != null) { contentBuilder.AppendHtml(errorMessage); } haveError = errorMessage != null; var inputTagBuilder = GenerateFileUpload(haveError); contentBuilder.AppendHtml(inputTagBuilder); return(contentBuilder); TagBuilder GenerateFileUpload(bool haveError) { var resolvedId = ResolveIdPrefix(); var resolvedName = ResolveName(); return(Generator.GenerateFileUpload( haveError, resolvedId, resolvedName, DescribedBy, InputAttributes.ToAttributeDictionary())); } }
HtmlString BuildPrevious() { if (Model.Page == 1) { return(new HtmlString(string.Empty)); } var text = PreviousText ?? T["Prev"]; _routeData[pageKey] = Model.Page - 1; var url = _urlHelper.RouteUrl(new UrlRouteContext { Values = _routeData }); var builder = new HtmlContentBuilder(); var htmlContentBuilder = builder .AppendHtml("<li class=\"page-item\">") .AppendHtml("<a class=\"page-link\" href=\"") .AppendHtml(url) .AppendHtml("\" aria-label=\"Previous\" >") .AppendHtml("<span aria-hidden=\"true\">") .AppendHtml(text) .AppendHtml("</span>") .AppendHtml("</a>") .AppendHtml("</li>"); return(htmlContentBuilder.ToHtmlString()); }
HtmlString BuildFirst() { if (Model.Page <= 2) { return(new HtmlString(string.Empty)); } _routeData.Remove(pageKey); var url = _urlHelper.RouteUrl(new UrlRouteContext { Values = _routeData }); var text = FirstText ?? T["«"]; var builder = new HtmlContentBuilder(); var htmlContentBuilder = builder .AppendHtml("<li class=\"page-item\">") .AppendHtml("<a class=\"page-link\" href=\"") .AppendHtml(url) .AppendHtml("\" aria-label=\"Previous\" >") .AppendHtml("<span aria-hidden=\"true\">") .AppendHtml(text) .AppendHtml("</span>") .AppendHtml("</a>") .AppendHtml("</li>"); return(htmlContentBuilder.ToHtmlString()); }
protected virtual IHtmlContent GenerateCheckBox( ModelExplorer modelExplorer, string expression, bool?isChecked, object htmlAttributes) { var checkbox = _htmlGenerator.GenerateCheckBox( ViewContext, modelExplorer, expression, isChecked, htmlAttributes); var hiddenForCheckboxTag = _htmlGenerator.GenerateHiddenForCheckbox(ViewContext, modelExplorer, expression); if (checkbox == null || hiddenForCheckboxTag == null) { return(HtmlString.Empty); } var checkboxContent = new HtmlContentBuilder().AppendHtml(checkbox); if (ViewContext.FormContext.CanRenderAtEndOfForm) { ViewContext.FormContext.EndOfFormContent.Add(hiddenForCheckboxTag); } else { checkboxContent.AppendHtml(hiddenForCheckboxTag); } return(checkboxContent); }
public void CopyTo_DoesDeepCopy() { // Arrange var source = new HtmlContentBuilder(); var nested = new HtmlContentBuilder(); source.AppendHtml(nested); nested.AppendHtml(new TestHtmlContent("hello")); source.Append("Test"); var destination = new HtmlContentBuilder(); destination.Append("some-content"); // Act source.CopyTo(destination); // Assert Assert.Equal(2, source.Entries.Count); Assert.Equal(1, nested.Entries.Count); Assert.Equal(3, destination.Entries.Count); Assert.Equal("some-content", Assert.IsType <string>(destination.Entries[0])); Assert.Equal(new TestHtmlContent("hello"), Assert.IsType <TestHtmlContent>(destination.Entries[1])); Assert.Equal("Test", Assert.IsType <string>(destination.Entries[2])); }
public static IHtmlContent RAToolbarEditorFor <TModel, TProperty>( this IHtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, object htmlAttributes = null, SelectList selectList = null, RAEditorType?editorTypeOverride = null, string displayLabel = null, string displayLabelClass = null, string selectListOptionLabel = null) { var modelExplorer = htmlHelper.GetModelExplorer(expression); var content = new HtmlContentBuilder(); var label = String.IsNullOrEmpty(displayLabel) ? modelExplorer.GetPropertyDisplayName() : displayLabel; if (!String.IsNullOrEmpty(label)) { var id = htmlHelper.GenerateIdFromName( htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlHelper.GetExpressionText(expression))); content.AppendFormat("<label for='{0}' class='ra-toolbar-label {1}'>{2}:</label>", id, displayLabelClass, label); } content.AppendHtml(htmlHelper.GetEditorFor(expression, modelExplorer, htmlAttributes, selectList, editorTypeOverride, true, selectListOptionLabel)); return(content); }
private static IHtmlContent RenderBootstrapFormCheckGroup <TModel, TResult>(this IHtmlHelper <TModel> helper, Expression <Func <TModel, TResult> > expression, FormCheckType formCheckType, IEnumerable <SelectListItem> selectListItems, LayoutDirection layoutDirection = LayoutDirection.Horizontal, object?htmlAttributes = null) { var result = new HtmlContentBuilder(); foreach (var item in selectListItems) { var inputTag = new TagBuilder("input") { TagRenderMode = TagRenderMode.SelfClosing }; inputTag.Attributes.Add("id", "_" + Crypto.RandomString()); inputTag.Attributes.Add("name", helper.NameFor(expression)); inputTag.Attributes.Add("value", item.Value); inputTag.Attributes.Add("type", formCheckType == FormCheckType.Switch ? "checkbox" : formCheckType.ToLower()); if (item.Selected) { inputTag.Attributes.Add("checked", "checked"); } inputTag.MergeAttributes(htmlAttributes); var additionalCssClass = (layoutDirection == LayoutDirection.Horizontal ? "form-check-inline custom-control-inline" : ""); var formCheck = BootstrapFormCheck(inputTag, formCheckType, item.Text, additionalCssClass); result.AppendHtml(formCheck); } return(result); }
public static IHtmlContent AddLink <T>(this IHtmlHelper <T> htmlHelper, string linkText, string container, string counter, string collection, Type nestedType) { var ticks = DateTime.UtcNow.Ticks; System.Diagnostics.Debug.WriteLine("\n"); var nestedObject = Activator.CreateInstance(nestedType); var temp = htmlHelper.EditorFor(x => nestedObject); var step1 = temp.ToString(); var step2 = step1.JsEncode(); System.Diagnostics.Debug.WriteLine("input: " + htmlHelper + ", " + linkText + ", " + container + ", " + counter + ", " + collection + ", " + nestedType); System.Diagnostics.Debug.WriteLine("HtmlHelper: " + temp); System.Diagnostics.Debug.WriteLine("ToString: " + step1); System.Diagnostics.Debug.WriteLine("JsEncode: " + step2); System.Diagnostics.Debug.WriteLine("\n"); var partial = step2; partial = partial.Replace("id=\\\"nestedObject", "id=\\\"" + collection + "_" + ticks + "_"); partial = partial.Replace("name=\\\"nestedObject", "name=\\\"" + collection + "[" + ticks + "]"); var js = string.Format("javascript:addNestedForm('{0}', '{1}', '{2}', '{3}'); return false;", container, counter, ticks, partial); TagBuilder tb = new TagBuilder("a"); tb.Attributes.Add("href", "#"); tb.Attributes.Add("onclick", js); tb.TagRenderMode = TagRenderMode.Normal; tb.InnerHtml.Append(linkText); HtmlContentBuilder result = new HtmlContentBuilder(); return(result.AppendHtml(tb)); }
HtmlString BuildLast() { if (Model.Page >= _totalPageCount - 1) { return(new HtmlString(string.Empty)); } var text = LastText ?? T["»"]; _routeData[pageKey] = _totalPageCount; var url = _urlHelper.RouteUrl(new UrlRouteContext { Values = _routeData }); var builder = new HtmlContentBuilder(); var htmlContentBuilder = builder .AppendHtml("<li class=\"page-item\">") .AppendHtml("<a class=\"page-link\" href=\"") .AppendHtml(url) .AppendHtml("\" aria-label=\"Last\">") .AppendHtml("<span aria-hidden=\"true\">") .AppendHtml(text) .AppendHtml("</span>") .AppendHtml("</a>") .AppendHtml("</li>"); return(htmlContentBuilder.ToHtmlString()); }
HtmlString BuildLabel() { var page = T["Page"]; var of = T["of"]; var results = T["Results"]; var builder = new HtmlContentBuilder(); var htmlContentBuilder = builder .AppendHtml("<li class=\"page-item\">") .AppendHtml("<div class=\"p-2 text-muted\">") .Append(page) .Append(" ") .Append(Model.Page.ToString()) .Append(" ") .Append(of) .Append(" ") .Append(_totalPageCount.ToString()) .Append(", ") .Append(Model.Total.ToString()) .Append(" ") .Append(results) .AppendHtml("</div>") .AppendHtml("</li>");; return(htmlContentBuilder.ToHtmlString()); }
/// <summary> /// Render all session modals using a partial view /// </summary> /// <typeparam name="TModal">The type of modal to render</typeparam> /// <param name="helper">The <see cref="IHtmlHelper"/> to extend rendering</param> /// <param name="modalManager">The modal manager which contains all the modals to render</param> /// <param name="partialViewName">The name of the partial view to use when rendering</param> /// <param name="clearModalsAfterRendering">Whether to clear the modals from the session after they have all been rendered</param> /// <returns>All the modals rendered as HTML</returns> /// <exception cref="ArgumentNullException"><paramref name="helper"/> or <paramref name="modalManager"/> or <paramref name="partialViewName"/> is <see langword="null"/></exception> public static IHtmlContent RenderModals <TModal>(this IHtmlHelper helper, IModalManager <TModal> modalManager, string partialViewName, bool clearModalsAfterRendering = true) where TModal : IModalViewModel { if (helper is null) { throw new ArgumentNullException(nameof(helper)); } if (modalManager is null) { throw new ArgumentNullException(nameof(modalManager)); } if (partialViewName is null) { throw new ArgumentNullException(nameof(partialViewName)); } IHtmlContentBuilder content = new HtmlContentBuilder(); foreach (var modal in modalManager.Get()) { content.AppendHtml(helper.Partial(partialViewName, modal)); } if (clearModalsAfterRendering) { modalManager.Clear(); } return(content); }
/// <summary> /// Join IHtmlContents them with separator /// </summary> public static IHtmlContent JoinList(this IHtmlHelper self, string rawSeparator, IEnumerable <IHtmlContent> contents) { var builder = new HtmlContentBuilder(); var writeSep = false; foreach (var c in contents) { if (writeSep) { builder.AppendHtml(rawSeparator); } writeSep = true; builder.AppendHtml(c); } return(builder); }
public void MoveTo_DoesDeepMove() { // Arrange var source = new HtmlContentBuilder(); var nested = new HtmlContentBuilder(); source.AppendHtml(nested); nested.AppendHtml(new TestHtmlContent("hello")); source.Append("Test"); var destination = new HtmlContentBuilder(); destination.Append("some-content"); // Act source.MoveTo(destination); // Assert Assert.Equal(0, source.Count); Assert.Equal(0, nested.Count); Assert.Equal(3, destination.Count); Assert.Collection( destination.Entries, entry => Assert.Equal("some-content", Assert.IsType <string>(entry)), entry => Assert.Equal(new TestHtmlContent("hello"), Assert.IsType <TestHtmlContent>(entry)), entry => Assert.Equal("Test", Assert.IsType <string>(entry))); }
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 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 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; }