public override void Process(TagHelperContext context, TagHelperOutput output) { string menuUrl = _UrlHelper.Action(ActionName, ControllerName); output.TagName = ""; var a = new TagBuilder("a"); a.MergeAttribute("href", $"{menuUrl}"); a.MergeAttribute("class", "item"); a.InnerHtml.Append(MenuText); var routeData = ViewContext.RouteData.Values; var currentController = routeData["controller"]; var currentAction = routeData["action"]; if (String.Equals(ActionName, currentAction as string, StringComparison.OrdinalIgnoreCase) && String.Equals(ControllerName, currentController as string, StringComparison.OrdinalIgnoreCase)) { a.AddCssClass("active"); a.AddCssClass("blue"); } output.Content.SetContent(a); }
public override void Process(TagHelperContext context, TagHelperOutput output) { var builder = new TagBuilder("h2", HtmlHelper.HtmlEncoder); var title = ViewContext.ViewBag.Title; builder.InnerHtml = HtmlHelper.Encode(title); output.PreContent.SetContent(builder.ToString()); }
public override async void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; output.AppendClass("widget-box"); output.AppendClass(Class); var originalContent = await output.GetChildContentAsync(); var innerHtml = originalContent.GetContent(); output.Content.Clear(); if (!innerHtml.Contains(WidgetBoxHeaderHelper.HeaderCss)) { // user is taking easy/lazy way of declaring the widget box output.Content.Append(WidgetBoxHeaderHelper.GetFullHeader(Title, IsCollapsible)); var widgetBodyDiv = WidgetBoxBodyHelper.GetFullBodyInternals(Padding, innerHtml); output.Content.Append(widgetBodyDiv); } else { // user is doing the hardwork themselves output.Content.AppendHtml(innerHtml); } base.Process(context, output); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; var pre = string.Format( "<ul class=\"pagination\" search-form-target=\"{0}\" update-link=\"{1}\" update-target=\"{2}\">", SearchFormTarget, UpdateLink, UpdateTarget); output.PreContent.SetContent(pre); var items = new StringBuilder(); for (var i = 1; i <= TotalPages; i++) { var li = string.Format( @"<li" + ((i == CurrentPage)?" class=\"active\"":"") + @"> <a href='{0}' title='{1}'>{2}</a> </li>", i, "Click to go to page {i}", i); items.AppendLine(li); } output.Content.SetContent(items.ToString()); output.PostContent.SetContent("</ul>"); output.Attributes.Clear(); output.Attributes.Add("class", "paged-list"); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var bytes = await _redisCache.GetAsync(context.UniqueId); string content; if (bytes == null) { var childContent = await output.GetChildContentAsync(); content = childContent.GetContent(); bytes = Encoding.UTF8.GetBytes(content); await _redisCache.SetAsync(context.UniqueId, bytes, new DistributedCacheEntryOptions { AbsoluteExpiration = AbsoluteExpiration, AbsoluteExpirationRelativeToNow = RelativeAbsoluteExpiration, SlidingExpiration = SlidingExpiration }); } else { content = Encoding.UTF8.GetString(bytes); } output.SuppressOutput(); // Unsupress by setting the content again. output.Content.SetHtmlContent(content); }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (!string.IsNullOrEmpty(DatatablesEdit)) output.Attributes.Add("data-edit", DatatablesEdit); if (!string.IsNullOrEmpty(DatatablesDelete)) output.Attributes.Add("data-delete", DatatablesDelete); if (!string.IsNullOrEmpty(DatatablesCreate)) output.Attributes.Add("data-create", DatatablesCreate); if (!string.IsNullOrEmpty(DatatablesEditRowSelect)) output.Attributes.Add("data-edit-row-select", DatatablesEditRowSelect); if (!string.IsNullOrEmpty(DatatablesEditButton)) output.Attributes.Add("data-edit-button", DatatablesEditButton); if (!string.IsNullOrEmpty(DatatablesDeleteButton)) output.Attributes.Add("data-delete-button", DatatablesDeleteButton); if (!string.IsNullOrEmpty(DatatablesCreateButton)) output.Attributes.Add("data-create-button", DatatablesCreateButton); if (!string.IsNullOrEmpty(DatatablesLang)) output.Attributes.Add("data-language", DatatablesLang); if (!string.IsNullOrEmpty(Lengthmenu)) output.Attributes.Add("data-lengthmenu", Lengthmenu); if (!Savestate != null) output.Attributes.Add("data-savestate", Savestate); if (!string.IsNullOrEmpty(Url)) output.Attributes.Add("data-url", Url); return Task.FromResult(0); }
/// <summary> /// Calls the <see cref="ITagHelper.ProcessAsync"/> method on <see cref="ITagHelper"/>s. /// </summary> /// <param name="executionContext">Contains information associated with running <see cref="ITagHelper"/>s. /// </param> /// <returns>Resulting <see cref="TagHelperOutput"/> from processing all of the /// <paramref name="executionContext"/>'s <see cref="ITagHelper"/>s.</returns> public async Task<TagHelperOutput> RunAsync(TagHelperExecutionContext executionContext) { if (executionContext == null) { throw new ArgumentNullException(nameof(executionContext)); } var tagHelperContext = new TagHelperContext( executionContext.AllAttributes, executionContext.Items, executionContext.UniqueId); OrderTagHelpers(executionContext.TagHelpers); for (var i = 0; i < executionContext.TagHelpers.Count; i++) { executionContext.TagHelpers[i].Init(tagHelperContext); } var tagHelperOutput = new TagHelperOutput( executionContext.TagName, executionContext.HTMLAttributes, executionContext.GetChildContentAsync) { TagMode = executionContext.TagMode, }; for (var i = 0; i < executionContext.TagHelpers.Count; i++) { await executionContext.TagHelpers[i].ProcessAsync(tagHelperContext, tagHelperOutput); } return tagHelperOutput; }
/// <summary> /// Calls the <see cref="ITagHelper.ProcessAsync"/> method on <see cref="ITagHelper"/>s. /// </summary> /// <param name="executionContext">Contains information associated with running <see cref="ITagHelper"/>s. /// </param> /// <returns>Resulting <see cref="TagHelperOutput"/> from processing all of the /// <paramref name="executionContext"/>'s <see cref="ITagHelper"/>s.</returns> public async Task<TagHelperOutput> RunAsync(TagHelperExecutionContext executionContext) { if (executionContext == null) { throw new ArgumentNullException(nameof(executionContext)); } var tagHelperContext = new TagHelperContext( executionContext.AllAttributes, executionContext.Items, executionContext.UniqueId); var orderedTagHelpers = executionContext.TagHelpers.OrderBy(tagHelper => tagHelper.Order); foreach (var tagHelper in orderedTagHelpers) { tagHelper.Init(tagHelperContext); } var tagHelperOutput = new TagHelperOutput( executionContext.TagName, executionContext.HTMLAttributes, executionContext.GetChildContentAsync) { TagMode = executionContext.TagMode, }; foreach (var tagHelper in orderedTagHelpers) { await tagHelper.ProcessAsync(tagHelperContext, tagHelperOutput); } return tagHelperOutput; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (_bundleManager.Exists(Source)) { var result = (await _smidgeHelper.GenerateJsUrlsAsync(Source, Debug)).ToArray(); var currAttr = output.Attributes.ToDictionary(x => x.Name, x => x.Value); using (var writer = new StringWriter()) { foreach (var s in result) { var builder = new TagBuilder(output.TagName) { TagRenderMode = TagRenderMode.Normal }; builder.MergeAttributes(currAttr); builder.Attributes["src"] = s; builder.WriteTo(writer, _encoder); } writer.Flush(); output.PostElement.SetContent(new HtmlString(writer.ToString())); } //This ensures the original tag is not written. output.TagName = null; } else { //use what is there output.Attributes["src"] = Source; } }
public override void Process(TagHelperContext context, TagHelperOutput output) { // If a condition is set and evaluates to false, don't render the tag. if (Condition.HasValue && !Condition.Value) { output.SuppressOutput(); } }
public void TagName_CanSetToNullInCtor() { // Arrange & Act var tagHelperOutput = new TagHelperOutput(null); // Assert Assert.Null(tagHelperOutput.TagName); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = null; for (int i = 0; i < Count; i++) { output.Content.Append(await output.GetChildContentAsync()); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.Content.AppendHtml("<ul>"); if (Credentials != null) { foreach(KeyValuePair<string, Credential> pair in Credentials) { GenerateCredentialHtml(pair.Key, pair.Value, output); } } output.Content.AppendHtml("</ul>"); base.Process(context, output); }
public override async void Process(TagHelperContext context, TagHelperOutput output) { output.SuppressOutput(); var originalContent = await output.GetChildContentAsync(); var headerDiv = GetHeader(); headerDiv.InnerHtml.AppendHtml(originalContent.GetContent()); output.Content.Clear(); output.Content.Append(headerDiv); base.Process(context, output); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = null; var partialResult = _viewEngine.FindPartialView(ViewContext, Name); if (partialResult != null && partialResult.Success) { var partialViewData = new ViewDataDictionary(ViewContext.ViewData, Model); var partialWriter = new TagHelperContentWrapperTextWriter(ViewContext.Writer.Encoding, output.Content); var partialViewContext = new ViewContext(ViewContext, partialResult.View, partialViewData, partialWriter); await partialResult.View.RenderAsync(partialViewContext); } }
public override async void Process(TagHelperContext context, TagHelperOutput output) { output.SuppressOutput(); var originalContent = await output.GetChildContentAsync(); var bodyContainer = GetBodyContainer(Padding); bodyContainer.WidgetMain.InnerHtml.AppendHtml(originalContent.GetContent()); output.Content.Clear(); output.Content.Append(bodyContainer.WidgetBody); base.Process(context, output); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (Emoji == "smile") { output.Attributes.Add("title", "smile"); output.Content.SetContent(" :) "); output.TagMode = TagMode.StartTagAndEndTag; } else if (Emoji == "sad") { var childContent = await context.GetChildContentAsync(); output.Attributes.Add("title", "sad"); output.Content.Append(childContent.GetContent() + ":'("); } }
public void PostElement_SetContent_ChangesValue() { // Arrange var tagHelperOutput = new TagHelperOutput("p"); tagHelperOutput.PostElement.SetContent("Hello World"); // Act & Assert Assert.NotNull(tagHelperOutput.PreElement); Assert.NotNull(tagHelperOutput.PreContent); Assert.NotNull(tagHelperOutput.Content); Assert.NotNull(tagHelperOutput.PostContent); Assert.NotNull(tagHelperOutput.PostElement); Assert.Equal( "HtmlEncode[[Hello World]]", tagHelperOutput.PostElement.GetContent(new CommonTestEncoder())); }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (Controller != null && Action != null) { var methodParameters = output.Attributes.ToDictionary(attribute => attribute.Key, attribute => (object)attribute.Value); // We remove all attributes from the resulting HTML element because they're supposed to // be parameters to our final href value. output.Attributes.Clear(); output.Attributes["href"] = UrlHelper.Action(Action, Controller, methodParameters); output.PreContent.SetContent("My "); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; output.Attributes["class"] = "profile-info-row"; var sb = new StringBuilder(); sb.AppendFormat(@" <div class=""profile-info-name"">{0}</div> <div class=""profile-info-value""> <span>{1}</span> </div>", Name, Value); output.Content.Clear(); output.Content.AppendHtml(sb.ToString()); base.Process(context, output); }
public override void Process(TagHelperContext context, TagHelperOutput output) { var br = new TagBuilder("br"); br.TagRenderMode = TagRenderMode.SelfClosing; output.TagName = "div"; output.Attributes.Add("itemscope", null); output.Attributes.Add("itemtype", "http://schema.org/Organization"); var name = new TagBuilder("span"); name.MergeAttribute("itemprop", "name"); name.InnerHtml.Append(Organisation.Name); var address = new TagBuilder("address"); address.MergeAttribute("itemprop", "address"); address.MergeAttribute("itemscope", null); address.MergeAttribute("itemtype", "http://schema.org/PostalAddress"); var span = new TagBuilder("span"); span.MergeAttribute("itemprop", "streetAddress"); span.InnerHtml.Append(Organisation.StreetAddress); address.InnerHtml.Append(br); span = new TagBuilder("span"); span.MergeAttribute("itemprop", "addressLocality"); span.InnerHtml.Append(Organisation.AddressLocality); address.InnerHtml.Append(span); address.InnerHtml.Append(br); span = new TagBuilder("span"); span.MergeAttribute("itemprop", "addressRegion"); span.InnerHtml.Append(Organisation.AddressRegion); address.InnerHtml.Append(span); span = new TagBuilder("span"); span.MergeAttribute("itemprop", "postalCode"); span.InnerHtml.Append(Organisation.PostalCode); address.InnerHtml.Append(span); output.Content.Clear(); output.Content.Append(address); }
/// <inheritdoc /> /// <remarks>Does nothing if <see cref="For"/> is <c>null</c>.</remarks> public override void Process(TagHelperContext context, TagHelperOutput output) { var tagBuilder = Generator.GenerateTextArea( ViewContext, For.ModelExplorer, For.Name, rows: 0, columns: 0, htmlAttributes: null); if (tagBuilder != null) { // Overwrite current Content to ensure expression result round-trips correctly. output.Content.SetContent(tagBuilder.InnerHtml); output.MergeAttributes(tagBuilder); } }
public async Task GetChildContentAsync_PassesUseCachedResultAsExpected(bool expectedUseCachedResultValue) { // Arrange bool? useCachedResultValue = null; var output = new TagHelperOutput( tagName: "p", attributes: new TagHelperAttributeList(), getChildContentAsync: useCachedResult => { useCachedResultValue = useCachedResult; return Task.FromResult<TagHelperContent>(new DefaultTagHelperContent()); }); // Act await output.GetChildContentAsync(expectedUseCachedResultValue); // Assert Assert.Equal(expectedUseCachedResultValue, useCachedResultValue); }
public override void Process(TagHelperContext context, TagHelperOutput output) { StringBuilder sb = new StringBuilder(); // Build ClientSide Model sb.AppendLine("var Model = {"); sb.AppendLine("debug : " + JsonConvert.SerializeObject(Debugger.IsAttached) + ","); sb.AppendLine("controller : " + JsonConvert.SerializeObject(ViewContext.RouteData.Values["controller"]) + ","); sb.AppendLine("action : " + JsonConvert.SerializeObject(ViewContext.RouteData.Values["action"]) + ","); sb.AppendLine("httpMethod : " + JsonConvert.SerializeObject(_httpContextAccessor.HttpContext.Request.Method) + ","); sb.AppendLine("userAgent : " + JsonConvert.SerializeObject(_httpContextAccessor.HttpContext.Request.Headers["user-agent"])); //sb.AppendLine(" 'currentCulture' : " + JsonConvert.SerializeObject(Thread.CurrentThread.CurrentCulture.Name) + ","); //sb.AppendLine(" 'currentUiCulture' : " + JsonConvert.SerializeObject(Thread.CurrentThread.CurrentUICulture.Name)); sb.AppendLine("};"); // End script tag sb.AppendLine("</script>"); output.Content.Append(sb.ToString()); }
private void GenerateCredentialHtml(string key, Credential credential, TagHelperOutput output) { if (!string.IsNullOrEmpty(credential.Value)) { output.Content.AppendHtml("<li>"); output.Content.Append(key + "=" + credential.Value); output.Content.AppendHtml("</li>"); } else { output.Content.AppendHtml("<li>"); output.Content.Append(key); output.Content.AppendHtml("</li>"); output.Content.AppendHtml("<ul>"); foreach (KeyValuePair<string, Credential> pair in credential) { GenerateCredentialHtml(pair.Key, pair.Value, output); } output.Content.AppendHtml("</ul>"); } }
public async Task Process_AddsHiddenInputTag_FromEndOfFormContent( List<TagBuilder> tagBuilderList, string expectedOutput) { // Arrange var viewContext = new ViewContext(); var tagHelperOutput = new TagHelperOutput( tagName: "form", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult) => { Assert.True(viewContext.FormContext.CanRenderAtEndOfForm); foreach (var item in tagBuilderList) { viewContext.FormContext.EndOfFormContent.Add(item); } return Task.FromResult<TagHelperContent>(new DefaultTagHelperContent()); }); var tagHelperContext = new TagHelperContext( Enumerable.Empty<IReadOnlyTagHelperAttribute>(), new Dictionary<object, object>(), "someId"); var tagHelper = new RenderAtEndOfFormTagHelper { ViewContext = viewContext }; tagHelper.Init(tagHelperContext); // Act await tagHelper.ProcessAsync(context: tagHelperContext, output: tagHelperOutput); // Assert Assert.Equal(expectedOutput, tagHelperOutput.PostContent.GetContent()); }
public override void Process(TagHelperContext context, TagHelperOutput output) { var preHtml = string.Empty; var postHtml = string.Empty; if (output.Attributes.ContainsName("id") == false && string.IsNullOrEmpty(Id) == false) { output.Attributes.SetAttribute("id", Id); } if (output.Attributes.ContainsName("lay-filter") == false && output.Attributes.ContainsName("id") == true) { output.Attributes.SetAttribute("lay-filter", $"{output.Attributes["id"].Value}filter"); } if (string.IsNullOrEmpty(Class) == false) { output.Attributes.SetAttribute("class", Class); } if (Style == null) { Style = ""; } if (Width.HasValue) { Style += $" width:{Width}px;"; } if (Height.HasValue) { Style += $" height:{Height}px;"; } if (string.IsNullOrEmpty(Style) == false) { if (this is TreeTagHelper) { Style += " overflow:auto;"; } output.Attributes.SetAttribute("style", Style); } if (context.Items.ContainsKey("ipr")) { int?ipr = (int?)context.Items["ipr"]; if (ipr > 0) { int col = 12 / ipr.Value; if (Colspan != null) { col *= Colspan.Value; } preHtml = $@" <div class=""layui-col-md{col}""> " + preHtml; postHtml += @" </div> "; output.PreElement.SetHtmlContent(preHtml + output.PreElement.GetContent()); output.PostElement.AppendHtml(postHtml); } } //输出事件 switch (this) { case ComboBoxTagHelper item: if (item.LinkField != null) { if (!string.IsNullOrEmpty(item.TriggerUrl)) { //item.ChangeFunc = $"ff.LinkedChange('{item.TriggerUrl}/'+data.value,'{Core.Utils.GetIdByName(item.LinkField.Name)}');"; output.PostElement.AppendHtml($@" <script> var form = layui.form; form.on('select({output.Attributes["lay-filter"].Value})', function(data){{ {FormatFuncName(item.ChangeFunc)}; ff.LinkedChange('{item.TriggerUrl}/'+data.value,'{Core.Utils.GetIdByName(item.LinkField.ModelExplorer.Container.ModelType.Name + "."+ item.LinkField.Name)}','{item.LinkField.Name}'); }}); </script> "); } } else { if (string.IsNullOrEmpty(item.ChangeFunc) == false) { output.PostElement.AppendHtml($@" <script> var form = layui.form; form.on('select({output.Attributes["lay-filter"].Value})', function(data){{ {FormatFuncName(item.ChangeFunc)}; }}); </script> "); } } break; case CheckBoxTagHelper item: if (string.IsNullOrEmpty(item.ChangeFunc) == false) { output.PostContent.SetHtmlContent(output.PostContent.GetContent().Replace("type=\"checkbox\" ", $"type=\"checkbox\" lay-filter=\"{output.Attributes["lay-filter"].Value}\"")); output.PostElement.AppendHtml($@" <script> var form = layui.form; form.on('checkbox({output.Attributes["lay-filter"].Value})', function(data){{ {FormatFuncName(item.ChangeFunc)}; }}); </script> "); } break; case SwitchTagHelper item: if (string.IsNullOrEmpty(item.ChangeFunc) == false) { output.PostElement.AppendHtml($@" <script> var form = layui.form; form.on('switch({output.Attributes["lay-filter"].Value})', function(data){{ {FormatFuncName(item.ChangeFunc)}; }}); </script> "); } break; case RadioTagHelper item: if (string.IsNullOrEmpty(item.ChangeFunc) == false) { output.PostElement.SetHtmlContent(output.PostElement.GetContent().Replace("type=\"radio\" ", $"type=\"radio\" lay-filter=\"{output.Attributes["lay-filter"].Value}\"")); output.PostElement.AppendHtml($@" <script> var form = layui.form; form.on('radio({output.Attributes["lay-filter"].Value})', function(data){{ {FormatFuncName(item.ChangeFunc)}; }}); </script> "); } break; case TextBoxTagHelper item: if (string.IsNullOrEmpty(item.SearchUrl) == false) { output.PostElement.AppendHtml($@" <script> layui.autocomplete.render({{ elem: $('#{item.Id}')[0], url: '{item.SearchUrl}', cache: false, template_val: '{{{{d.Value}}}}', template_txt: '{{{{d.Text}}}}', onselect: function (resp) {{ $('#{item.Id}').val(resp.Value); }} }});</script> "); } break; } //如果是submitbutton,则在button前面加入一个区域用来定位输出后台返回的错误 if (output.TagName == "button" && output.Attributes.TryGetAttribute("lay-submit", out TagHelperAttribute ta) == true) { output.PreElement.SetHtmlContent($"<p id='{Id}errorholder'></p>" + output.PreElement.GetContent()); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.Content.AppendEncoded("root-content"); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "ul"; output.Attributes["class"] = "pagination pagination-sm"; if (CurrentPage == 0) CurrentPage = 1; var writer = new StringWriter(); var encoder = new HtmlEncoder(); var li = new TagBuilder("li"); var a = new TagBuilder("a"); if (CurrentPage > 10) { a.MergeAttribute("href", $"{Url}?Page={((CurrentPage - 1) / 10) * 10}{(SearchMode ? $"&SearchField={SearchField}&SearchQuery={SearchQuery}" : "")}"); a.InnerHtml.AppendHtml("◄"); } else { a.MergeAttribute("class", "disabled"); a.InnerHtml.AppendHtml("◁"); } li.InnerHtml.Append(a); li.WriteTo(writer, encoder); int firstPage = (CurrentPage - 1) / 10 * 10 + 1; int i; for (i = firstPage; i < firstPage + 10; i++) { if (i > TotalPages) break; li = new TagBuilder("li"); a = new TagBuilder("a"); if (i == CurrentPage) { li.MergeAttribute("class", "active"); a.MergeAttribute("href", "#"); } else { a.MergeAttribute("href", $"{Url}?Page={i}{(SearchMode ? $"&SearchField={SearchField}&SearchQuery={SearchQuery}" : "")}"); } a.InnerHtml.AppendHtml(i.ToString()); li.InnerHtml.Append(a); li.WriteTo(writer, encoder); } li = new TagBuilder("li"); a = new TagBuilder("a"); if (i < TotalPages) { a.MergeAttribute("href", $"{Url}?Page={i}{(SearchMode ? $"&SearchField={SearchField}&SearchQuery={SearchQuery}" : "")}"); a.InnerHtml.AppendHtml("►"); } else { a.MergeAttribute("class", "disabled"); a.InnerHtml.AppendHtml("▷"); } li.InnerHtml.Append(a); li.WriteTo(writer, encoder); output.Content.AppendHtml(writer.ToString()); }
protected virtual string SurroundInnerHtmlAndGet(TagHelperContext context, TagHelperOutput output, string innerHtml, bool isCheckbox) { return("<div class=\"" + (isCheckbox ? "custom-checkbox custom-control" : "form-group") + "\">" + Environment.NewLine + innerHtml + Environment.NewLine + "</div>"); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "select"; base.Process(context, output); }
protected virtual bool IsOutputHidden(TagHelperOutput inputTag) { return(inputTag.Attributes.Any(a => a.Name.ToLowerInvariant() == "type" && a.Value.ToString().ToLowerInvariant() == "hidden")); }
protected virtual async Task <(string, bool)> GetFormInputGroupAsHtmlAsync(TagHelperContext context, TagHelperOutput output) { var(inputTag, isCheckBox) = await GetInputTagHelperOutputAsync(context, output); var inputHtml = inputTag.Render(_encoder); var label = await GetLabelAsHtmlAsync(context, output, inputTag, isCheckBox); var info = GetInfoAsHtml(context, output, inputTag, isCheckBox); var validation = isCheckBox ? "" : await GetValidationAsHtmlAsync(context, output, inputTag); return(GetContent(context, output, label, inputHtml, validation, info, isCheckBox), isCheckBox); }
public async Task ProcessAsync_WithItems_AndNoModelExpression_GeneratesExpectedOutput() { // Arrange var originalAttributes = new TagHelperAttributeList { { "class", "form-control" }, }; var originalPostContent = "original content"; var expectedAttributes = new TagHelperAttributeList(originalAttributes); var selectItems = new SelectList(Enumerable.Range(0, 5)); var expectedOptions = "<option>HtmlEncode[[0]]</option>" + Environment.NewLine + "<option>HtmlEncode[[1]]</option>" + Environment.NewLine + "<option>HtmlEncode[[2]]</option>" + Environment.NewLine + "<option>HtmlEncode[[3]]</option>" + Environment.NewLine + "<option>HtmlEncode[[4]]</option>" + Environment.NewLine; var expectedPreContent = "original pre-content"; var expectedContent = "original content"; var expectedPostContent = originalPostContent + expectedOptions; var expectedTagName = "select"; var tagHelperContext = new TagHelperContext( allAttributes: new TagHelperAttributeList( Enumerable.Empty <TagHelperAttribute>()), items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( expectedTagName, originalAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.AppendHtml("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }) { TagMode = TagMode.SelfClosing, }; output.PreContent.AppendHtml(expectedPreContent); output.Content.AppendHtml(expectedContent); output.PostContent.AppendHtml(originalPostContent); var metadataProvider = new TestModelMetadataProvider(); var htmlGenerator = new TestableHtmlGenerator(metadataProvider); var viewContext = TestableHtmlGenerator.GetViewContext( model: null, htmlGenerator: htmlGenerator, metadataProvider: metadataProvider); var tagHelper = new SelectTagHelper(htmlGenerator) { Items = selectItems, ViewContext = viewContext, }; // Act tagHelper.Init(tagHelperContext); await tagHelper.ProcessAsync(tagHelperContext, output); // Assert Assert.Equal(TagMode.SelfClosing, output.TagMode); Assert.Equal(expectedAttributes, output.Attributes); Assert.Equal(expectedPreContent, output.PreContent.GetContent()); Assert.Equal(expectedContent, output.Content.GetContent()); Assert.Equal(expectedPostContent, HtmlContentUtilities.HtmlContentToString(output.PostContent)); Assert.Equal(expectedTagName, output.TagName); var kvp = Assert.Single(tagHelperContext.Items); Assert.Equal(typeof(SelectTagHelper), kvp.Key); Assert.Null(kvp.Value); }
public async Task ProcessAsyncInTemplate_WithItems_GeneratesExpectedOutput_DoesNotChangeSelectList( object model, Type containerType, Func <object> modelAccessor, NameAndId nameAndId, string expectedOptions) { // Arrange var originalAttributes = new TagHelperAttributeList { { "class", "form-control" }, }; var originalPostContent = "original content"; var expectedAttributes = new TagHelperAttributeList(originalAttributes) { { "id", nameAndId.Id }, { "name", nameAndId.Name }, { "valid", "from validation attributes" }, }; var expectedPreContent = "original pre-content"; var expectedContent = "original content"; var expectedPostContent = originalPostContent + expectedOptions; var expectedTagName = "select"; var metadataProvider = new TestModelMetadataProvider(); var containerMetadata = metadataProvider.GetMetadataForType(containerType); var containerExplorer = metadataProvider.GetModelExplorerForType(containerType, model); var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text"); var modelExplorer = containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor()); var modelExpression = new ModelExpression(name: string.Empty, modelExplorer: modelExplorer); var tagHelperContext = new TagHelperContext( allAttributes: new TagHelperAttributeList( Enumerable.Empty <TagHelperAttribute>()), items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( expectedTagName, originalAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.AppendHtml("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }) { TagMode = TagMode.SelfClosing, }; output.PreContent.AppendHtml(expectedPreContent); output.Content.AppendHtml(expectedContent); output.PostContent.AppendHtml(originalPostContent); var htmlGenerator = new TestableHtmlGenerator(metadataProvider) { ValidationAttributes = { { "valid", "from validation attributes" }, } }; var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider); viewContext.ViewData.TemplateInfo.HtmlFieldPrefix = nameAndId.Name; var items = new SelectList(new[] { "", "outer text", "inner text", "other text" }); var savedDisabled = items.Select(item => item.Disabled).ToList(); var savedGroup = items.Select(item => item.Group).ToList(); var savedSelected = items.Select(item => item.Selected).ToList(); var savedText = items.Select(item => item.Text).ToList(); var savedValue = items.Select(item => item.Value).ToList(); var tagHelper = new SelectTagHelper(htmlGenerator) { For = modelExpression, Items = items, ViewContext = viewContext, }; // Act tagHelper.Init(tagHelperContext); await tagHelper.ProcessAsync(tagHelperContext, output); // Assert Assert.Equal(TagMode.SelfClosing, output.TagMode); Assert.Equal(expectedAttributes, output.Attributes); Assert.Equal(expectedPreContent, output.PreContent.GetContent()); Assert.Equal(expectedContent, output.Content.GetContent()); Assert.Equal(expectedPostContent, HtmlContentUtilities.HtmlContentToString(output.PostContent)); Assert.Equal(expectedTagName, output.TagName); Assert.Single( tagHelperContext.Items, entry => (Type)entry.Key == typeof(SelectTagHelper)); Assert.Equal(savedDisabled, items.Select(item => item.Disabled)); Assert.Equal(savedGroup, items.Select(item => item.Group)); Assert.Equal(savedSelected, items.Select(item => item.Selected)); Assert.Equal(savedText, items.Select(item => item.Text)); Assert.Equal(savedValue, items.Select(item => item.Value)); }
/// <inheritdoc /> /// <remarks>Does nothing if user provides an <c>href</c> attribute.</remarks> public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "a"; if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } if (isAjax) { output.Attributes.Add("data-ajax", "true"); output.Attributes.Add("data-ajax-method", Method); output.Attributes.Add("data-ajax-mode", Mode); if (!string.IsNullOrEmpty(Update)) { output.Attributes.Add("data-ajax-update", Update); } if (!string.IsNullOrEmpty(AjaxLoading)) { output.Attributes.Add("data-ajax-loading", AjaxLoading); } if (!string.IsNullOrEmpty(OnBegin)) { output.Attributes.Add("data-ajax-begin", OnBegin); } if (!string.IsNullOrEmpty(OnComplete)) { output.Attributes.Add("data-ajax-complete", OnComplete); } } // If "href" is already set, it means the user is attempting to use a normal anchor. if (output.Attributes.ContainsName(Href)) { if (Action != null || Controller != null || Area != null || Page != null || PageHandler != null || Route != null || Protocol != null || Host != null || Fragment != null || (_routeValues != null && _routeValues.Count > 0)) { //throw new InvalidOperationException(); } return; } var routeLink = Route != null; var actionLink = Controller != null || Action != null; var pageLink = Page != null || PageHandler != null; if ((routeLink && actionLink) || (routeLink && pageLink) || (actionLink && pageLink)) { var message = string.Join( Environment.NewLine, //Resources.FormatCannotDetermineAttributeFor(Href, "<a>"), RouteAttributeName, ControllerAttributeName + ", " + ActionAttributeName, PageAttributeName + ", " + PageHandlerAttributeName); throw new InvalidOperationException(message); } RouteValueDictionary routeValues = null; if (_routeValues != null && _routeValues.Count > 0) { routeValues = new RouteValueDictionary(_routeValues); } if (Area != null) { // Unconditionally replace any value from asp-route-area. if (routeValues == null) { routeValues = new RouteValueDictionary(); } routeValues["area"] = Area; } TagBuilder tagBuilder; if (pageLink) { tagBuilder = Generator.GeneratePageLink( ViewContext, linkText: string.Empty, pageName: Page, pageHandler: PageHandler, protocol: Protocol, hostname: Host, fragment: Fragment, routeValues: routeValues, htmlAttributes: null); } else if (routeLink) { tagBuilder = Generator.GenerateRouteLink( ViewContext, linkText: string.Empty, routeName: Route, protocol: Protocol, hostName: Host, fragment: Fragment, routeValues: routeValues, htmlAttributes: null); } else { tagBuilder = Generator.GenerateActionLink( ViewContext, linkText: string.Empty, actionName: Action, controllerName: Controller, protocol: Protocol, hostname: Host, fragment: Fragment, routeValues: routeValues, htmlAttributes: null); } output.MergeAttributes(tagBuilder); }
public async Task ProcessAsync_GeneratesExpectedOutput( object model, Type containerType, Func <object> modelAccessor, NameAndId nameAndId, string ignored) { // Arrange var originalAttributes = new TagHelperAttributeList { { "class", "form-control" }, }; var originalPostContent = "original content"; var expectedAttributes = new TagHelperAttributeList(originalAttributes) { { "id", nameAndId.Id }, { "name", nameAndId.Name }, { "valid", "from validation attributes" }, }; var expectedPreContent = "original pre-content"; var expectedContent = "original content"; var expectedPostContent = originalPostContent; var expectedTagName = "not-select"; var metadataProvider = new TestModelMetadataProvider(); var containerMetadata = metadataProvider.GetMetadataForType(containerType); var containerExplorer = metadataProvider.GetModelExplorerForType(containerType, model); var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text"); var modelExplorer = containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor()); var modelExpression = new ModelExpression(nameAndId.Name, modelExplorer); var tagHelperContext = new TagHelperContext( allAttributes: new TagHelperAttributeList( Enumerable.Empty <TagHelperAttribute>()), items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( expectedTagName, originalAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }) { TagMode = TagMode.SelfClosing, }; output.PreContent.SetContent(expectedPreContent); output.Content.SetContent(expectedContent); output.PostContent.SetContent(originalPostContent); var htmlGenerator = new TestableHtmlGenerator(metadataProvider) { ValidationAttributes = { { "valid", "from validation attributes" }, } }; var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider); var tagHelper = new SelectTagHelper(htmlGenerator) { For = modelExpression, ViewContext = viewContext, }; // Act tagHelper.Init(tagHelperContext); await tagHelper.ProcessAsync(tagHelperContext, output); // Assert Assert.Equal(TagMode.SelfClosing, output.TagMode); Assert.Equal(expectedAttributes, output.Attributes); Assert.Equal(expectedPreContent, output.PreContent.GetContent()); Assert.Equal(expectedContent, output.Content.GetContent()); Assert.Equal(expectedPostContent, output.PostContent.GetContent()); Assert.Equal(expectedTagName, output.TagName); Assert.Single( tagHelperContext.Items, entry => (Type)entry.Key == typeof(SelectTagHelper)); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = TagHelper.Heading.ToHtmlTag(); output.Attributes.AddClass("card-title"); }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (Source.IsNullOrWhiteSpace()) { Source = Url.Action(DefaultSourceAction); } if (GridClass.IsNullOrWhiteSpace()) { GridClass = DefaultClass; } if (ModelType == null) { ModelType = ViewContext.ViewData.ModelMetadata.ModelType; } var viewConfig = ViewConfigureAttribute.GetAttribute(ModelType); StringBuilder tableHeaderBuilder = new StringBuilder(); StringBuilder tableSearchBuilder = new StringBuilder(); if (viewConfig != null) { var primaryKey = viewConfig.MetaData.Properties.Select(m => m.Value).FirstOrDefault(m => m.CustomAttributes.Any(attr => attr.AttributeType == typeof(KeyAttribute))); viewConfig.InitDisplayName(); if ((EditAble ?? true) && primaryKey != null) { string name = primaryKey.Name.FirstCharToLowerCase(); if (name.Length == 2) { name = name.ToLower(); } if (Edit.IsNullOrWhiteSpace()) { Edit = Url.Action(DefaultEditAction) + "/{" + name + "}"; } if (Delete.IsNullOrWhiteSpace()) { Delete = Url.Action(DefaultDeleteAction) + "/{" + name + "}"; } string manager = EditLinkTemplate.FormatWith(Edit); if (DeleteAble ?? true) { manager += " " + DeleteLinkTemplate.FormatWith(Delete); } tableHeaderBuilder.AppendFormat(TableHeadStructure, string.Empty, WebUtility.HtmlEncode(manager), string.Empty, "操作", string.Empty, Query.Operators.None, string.Empty, string.Empty); tableSearchBuilder.Append(TableSearchStructure); } var columns = viewConfig.GetViewPortDescriptors(true) .Where(m => m.IsShowInGrid) .Each(m => { var dropDown = m as DropDownListDescriptor; StringBuilder optionBuilder = new StringBuilder(); if (dropDown != null) { foreach (var item in dropDown.OptionItems) { optionBuilder.AppendFormat("{{\"name\":\"{0}\",\"value\":\"{1}\"}},", item.Value, item.Key); } } else if (m.DataType == typeof(bool) || m.DataType == typeof(bool?)) { optionBuilder.AppendFormat("{{\"name\":\"{0}\",\"value\":\"{1}\"}},", "是", "true"); optionBuilder.AppendFormat("{{\"name\":\"{0}\",\"value\":\"{1}\"}},", "否", "false"); } tableHeaderBuilder.AppendFormat(TableHeadStructure, m.Name.FirstCharToLowerCase(), WebUtility.HtmlEncode(m.GridColumnTemplate), OrderAsc == m.Name ? "asc" : OrderDesc == m.Name ? "desc" : "", m.DisplayName, optionBuilder.Length == 0 ? string.Empty : WebUtility.HtmlEncode($"[{optionBuilder.ToString().Trim(',')}]"), m.SearchOperator, m.DataType.Name, (m as TextBoxDescriptor)?.JavaScriptDateFormat); tableSearchBuilder.Append(TableSearchStructure); }); } output.TagName = "div"; output.Attributes.Add("class", "container-fluid"); output.Content.SetHtmlContent(TableStructure.FormatWith(GridClass, Source, tableHeaderBuilder, tableSearchBuilder)); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="output"></param> public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "h6"; output.AddClass("dropdown-header"); base.Process(context, output); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { await output.GetChildContentAsync(); }
public async Task ProcessAsync_CallsGeneratorWithExpectedValues_ItemsAndAttribute( IEnumerable <SelectListItem> inputItems, string attributeName, string attributeValue, IEnumerable <SelectListItem> expectedItems) { // Arrange var contextAttributes = new TagHelperAttributeList { // Provided for completeness. Select tag helper does not confirm AllAttributes set is consistent. { attributeName, attributeValue }, }; var originalAttributes = new TagHelperAttributeList { { attributeName, attributeValue }, }; var propertyName = "Property1"; var expectedTagName = "select"; var tagHelperContext = new TagHelperContext( contextAttributes, items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( expectedTagName, originalAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }); var metadataProvider = new EmptyModelMetadataProvider(); string model = null; var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(string), model); var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator.Object, metadataProvider); // Simulate a (model => model) scenario. E.g. the calling helper may appear in a low-level template. var modelExpression = new ModelExpression(string.Empty, modelExplorer); viewContext.ViewData.TemplateInfo.HtmlFieldPrefix = propertyName; var currentValues = new string[0]; htmlGenerator .Setup(real => real.GetCurrentValues( viewContext, modelExplorer, string.Empty, // expression false)) // allowMultiple .Returns(currentValues) .Verifiable(); htmlGenerator .Setup(real => real.GenerateSelect( viewContext, modelExplorer, null, // optionLabel string.Empty, // expression expectedItems, currentValues, false, // allowMultiple null)) // htmlAttributes .Returns((TagBuilder)null) .Verifiable(); var tagHelper = new SelectTagHelper(htmlGenerator.Object) { For = modelExpression, Items = inputItems, ViewContext = viewContext, }; // Act tagHelper.Init(tagHelperContext); await tagHelper.ProcessAsync(tagHelperContext, output); // Assert htmlGenerator.Verify(); var keyValuePair = Assert.Single( tagHelperContext.Items, entry => (Type)entry.Key == typeof(SelectTagHelper)); var actualCurrentValues = Assert.IsType <CurrentValues>(keyValuePair.Value); Assert.Same(currentValues, actualCurrentValues.Values); }
public override void Process(TagHelperContext tagHelperContext, TagHelperOutput output) { ContentItemMetadata metadata = null; ContentItem contentItem = null; var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext); if (DisplayFor != null) { contentItem = DisplayFor; metadata = _contentManager.PopulateAspect <ContentItemMetadata>(DisplayFor); if (metadata.DisplayRouteValues == null) { return; } ApplyRouteValues(tagHelperContext, metadata.DisplayRouteValues); output.Attributes.SetAttribute("href", urlHelper.Action(metadata.DisplayRouteValues["action"].ToString(), metadata.DisplayRouteValues)); } else if (EditFor != null) { contentItem = EditFor; metadata = _contentManager.PopulateAspect <ContentItemMetadata>(EditFor); if (metadata.EditorRouteValues == null) { return; } ApplyRouteValues(tagHelperContext, metadata.EditorRouteValues); output.Attributes.SetAttribute("href", urlHelper.Action(metadata.EditorRouteValues["action"].ToString(), metadata.EditorRouteValues)); } else if (AdminFor != null) { contentItem = AdminFor; metadata = _contentManager.PopulateAspect <ContentItemMetadata>(AdminFor); if (metadata.AdminRouteValues == null) { return; } ApplyRouteValues(tagHelperContext, metadata.AdminRouteValues); output.Attributes.SetAttribute("href", urlHelper.Action(metadata.AdminRouteValues["action"].ToString(), metadata.AdminRouteValues)); } else if (RemoveFor != null) { contentItem = RemoveFor; metadata = _contentManager.PopulateAspect <ContentItemMetadata>(RemoveFor); if (metadata.RemoveRouteValues == null) { return; } ApplyRouteValues(tagHelperContext, metadata.RemoveRouteValues); output.Attributes.SetAttribute("href", urlHelper.Action(metadata.RemoveRouteValues["action"].ToString(), metadata.RemoveRouteValues)); } else if (CreateFor != null) { contentItem = CreateFor; metadata = _contentManager.PopulateAspect <ContentItemMetadata>(CreateFor); if (metadata.CreateRouteValues == null) { return; } ApplyRouteValues(tagHelperContext, metadata.CreateRouteValues); output.Attributes.SetAttribute("href", urlHelper.Action(metadata.CreateRouteValues["action"].ToString(), metadata.CreateRouteValues)); } // A self closing anchor tag will be rendered using the display text if (output.TagMode == TagMode.SelfClosing && metadata != null) { output.TagMode = TagMode.StartTagAndEndTag; if (!string.IsNullOrEmpty(metadata.DisplayText)) { output.Content.Append(metadata.DisplayText); } else { var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType); output.Content.Append(typeDefinition.ToString()); } } return; }
public async Task TagHelper_CallsGeneratorWithExpectedValues_RealModelType( Type modelType, object model, bool allowMultiple) { // Arrange var contextAttributes = new TagHelperAttributeList( Enumerable.Empty <TagHelperAttribute>()); var originalAttributes = new TagHelperAttributeList(); var propertyName = "Property1"; var tagName = "select"; var tagHelperContext = new TagHelperContext( contextAttributes, items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( tagName, originalAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }); var metadataProvider = new EmptyModelMetadataProvider(); var modelExplorer = metadataProvider.GetModelExplorerForType(modelType, model); var modelExpression = new ModelExpression(propertyName, modelExplorer); var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator.Object, metadataProvider); var currentValues = new string[0]; htmlGenerator .Setup(real => real.GetCurrentValues( viewContext, modelExplorer, propertyName, // expression allowMultiple)) .Returns(currentValues) .Verifiable(); htmlGenerator .Setup(real => real.GenerateSelect( viewContext, modelExplorer, null, // optionLabel propertyName, // expression It.IsAny <IEnumerable <SelectListItem> >(), currentValues, allowMultiple, null)) // htmlAttributes .Returns((TagBuilder)null) .Verifiable(); var tagHelper = new SelectTagHelper(htmlGenerator.Object) { For = modelExpression, ViewContext = viewContext, }; // Act tagHelper.Init(tagHelperContext); await tagHelper.ProcessAsync(tagHelperContext, output); // Assert htmlGenerator.Verify(); var keyValuePair = Assert.Single( tagHelperContext.Items, entry => (Type)entry.Key == typeof(SelectTagHelper)); var actualCurrentValues = Assert.IsType <CurrentValues>(keyValuePair.Value); Assert.Same(currentValues, actualCurrentValues.Values); }
protected virtual string GetIdAttributeAsString(TagHelperOutput inputTag) { var idAttr = inputTag.Attributes.FirstOrDefault(a => a.Name == "id"); return(idAttr != null ? "for=\"" + idAttr.Value + "\"" : ""); }
protected virtual async Task <(TagHelperOutput, bool)> GetInputTagHelperOutputAsync(TagHelperContext context, TagHelperOutput output) { var tagHelper = GetInputTagHelper(context, output); var inputTagHelperOutput = await tagHelper.ProcessAndGetOutputAsync(GetInputAttributes(context, output), context, "input"); ConvertToTextAreaIfTextArea(inputTagHelperOutput); AddDisabledAttribute(inputTagHelperOutput); AddAutoFocusAttribute(inputTagHelperOutput); var isCheckbox = IsInputCheckbox(context, output, inputTagHelperOutput.Attributes); AddFormControlClass(context, output, isCheckbox, inputTagHelperOutput); AddReadOnlyAttribute(inputTagHelperOutput); AddPlaceholderAttribute(inputTagHelperOutput); AddInfoTextId(inputTagHelperOutput); return(inputTagHelperOutput, isCheckbox); }
protected virtual async Task <string> GetValidationAsHtmlAsync(TagHelperContext context, TagHelperOutput output, TagHelperOutput inputTag) { if (IsOutputHidden(inputTag)) { return(""); } var validationMessageTagHelper = new ValidationMessageTagHelper(_generator) { For = TagHelper.AspFor, ViewContext = TagHelper.ViewContext }; var attributeList = new TagHelperAttributeList { { "class", "text-danger" } }; return(await validationMessageTagHelper.RenderAsync(attributeList, context, _encoder, "span", TagMode.StartTagAndEndTag)); }
private void AddFormControlClass(TagHelperContext context, TagHelperOutput output, bool isCheckbox, TagHelperOutput inputTagHelperOutput) { var className = "form-control"; if (isCheckbox) { className = "custom-control-input"; } inputTagHelperOutput.Attributes.AddClass(className + " " + GetSize(context, output)); }
/// <summary> /// Synchronously executes the <see cref="TagHelper"/> with the given /// <paramref name="context"/> and <paramref name="output"/>. /// </summary> /// <param name="context">Contains information associated with the current HTML tag.</param> /// <param name="output">A stateful HTML element used to generate an HTML tag.</param> public override void Process(TagHelperContext context, TagHelperOutput output) { output.Content.SetHtmlContent(this.ToString()); output.TagName = null; }
protected virtual bool IsInputCheckbox(TagHelperContext context, TagHelperOutput output, TagHelperAttributeList attributes) { return(attributes.Any(a => a.Value != null && a.Name == "type" && a.Value.ToString() == "checkbox")); }
/// <inheritdoc /> /// <remarks>Does nothing if <see cref="For"/> is <c>null</c>.</remarks> /// <exception cref="InvalidOperationException"> /// Thrown if <see cref="Format"/> is non-<c>null</c> but <see cref="For"/> is <c>null</c>. /// </exception> public override void Process(TagHelperContext context, TagHelperOutput output) { // Pass through attributes that are also well-known HTML attributes. Must be done prior to any copying // from a TagBuilder. if (InputTypeName != null) { output.CopyHtmlAttribute("type", context); } if (Value != null) { output.CopyHtmlAttribute(nameof(Value), context); } // Note null or empty For.Name is allowed because TemplateInfo.HtmlFieldPrefix may be sufficient. // IHtmlGenerator will enforce name requirements. var metadata = For.Metadata; var modelExplorer = For.ModelExplorer; if (metadata == null) { throw new InvalidOperationException(Resources.FormatTagHelpers_NoProvidedMetadata( "<input>", ForAttributeName, nameof(IModelMetadataProvider), For.Name)); } string inputType; string inputTypeHint; if (string.IsNullOrEmpty(InputTypeName)) { // Note GetInputType never returns null. inputType = GetInputType(modelExplorer, out inputTypeHint); } else { inputType = InputTypeName.ToLowerInvariant(); inputTypeHint = null; } // inputType may be more specific than default the generator chooses below. if (!output.Attributes.ContainsName("type")) { output.Attributes["type"] = inputType; } TagBuilder tagBuilder; switch (inputType) { case "checkbox": GenerateCheckBox(modelExplorer, output); return; case "hidden": tagBuilder = Generator.GenerateHidden( ViewContext, modelExplorer, For.Name, value: For.Model, useViewData: false, htmlAttributes: null); break; case "password": tagBuilder = Generator.GeneratePassword( ViewContext, modelExplorer, For.Name, value: null, htmlAttributes: null); break; case "radio": tagBuilder = GenerateRadio(modelExplorer); break; default: tagBuilder = GenerateTextBox(modelExplorer, inputTypeHint, inputType); break; } if (tagBuilder != null) { // This TagBuilder contains the one <input/> element of interest. Since this is not the "checkbox" // special-case, output is a self-closing element no longer guaranteed. output.MergeAttributes(tagBuilder); output.Content.Append(tagBuilder.InnerHtml); } }
protected virtual async Task <string> GetLabelAsHtmlAsync(TagHelperContext context, TagHelperOutput output, TagHelperOutput inputTag, bool isCheckbox) { if (IsOutputHidden(inputTag)) { return(""); } if (string.IsNullOrEmpty(TagHelper.Label)) { return(await GetLabelAsHtmlUsingTagHelperAsync(context, output, isCheckbox) + GetRequiredSymbol(context, output)); } var checkboxClass = isCheckbox ? "class=\"custom-control-label\" " : ""; return("<label " + checkboxClass + GetIdAttributeAsString(inputTag) + ">" + TagHelper.Label + "</label>" + GetRequiredSymbol(context, output)); }
/// <inheritdoc /> public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } // Pass through attribute that is also a well-known HTML attribute. if (Src != null) { output.CopyHtmlAttribute(SrcAttributeName, context); } // If there's no "src" attribute in output.Attributes this will noop. ProcessUrlAttribute(SrcAttributeName, output); // Retrieve the TagHelperOutput variation of the "src" attribute in case other TagHelpers in the // pipeline have touched the value. If the value is already encoded this ScriptTagHelper may // not function properly. Src = output.Attributes[SrcAttributeName]?.Value as string; if (!AttributeMatcher.TryDetermineMode(context, ModeDetails, Compare, out var mode)) { // No attributes matched so we have nothing to do return; } if (AppendVersion == true) { EnsureFileVersionProvider(); if (Src != null) { var index = output.Attributes.IndexOfName(SrcAttributeName); var existingAttribute = output.Attributes[index]; output.Attributes[index] = new TagHelperAttribute( existingAttribute.Name, FileVersionProvider.AddFileVersionToPath(ViewContext.HttpContext.Request.PathBase, Src), existingAttribute.ValueStyle); } } var builder = output.PostElement; builder.Clear(); if (mode == Mode.GlobbedSrc || mode == Mode.Fallback && !string.IsNullOrEmpty(SrcInclude)) { BuildGlobbedScriptTags(output.Attributes, builder); if (string.IsNullOrEmpty(Src)) { // Only SrcInclude is specified. Don't render the original tag. output.TagName = null; output.Content.SetContent(string.Empty); } } if (mode == Mode.Fallback) { if (TryResolveUrl(FallbackSrc, resolvedUrl: out string resolvedUrl)) { FallbackSrc = resolvedUrl; } BuildFallbackBlock(output.Attributes, builder); } }
protected virtual string GetInfoAsHtml(TagHelperContext context, TagHelperOutput output, TagHelperOutput inputTag, bool isCheckbox) { if (IsOutputHidden(inputTag)) { return(""); } if (isCheckbox) { return(""); } var text = ""; if (!string.IsNullOrEmpty(TagHelper.InfoText)) { text = TagHelper.InfoText; } else { var infoAttribute = TagHelper.AspFor.ModelExplorer.GetAttribute <InputInfoText>(); if (infoAttribute != null) { text = infoAttribute.Text; } else { return(""); } } var idAttr = inputTag.Attributes.FirstOrDefault(a => a.Name == "id"); var localizedText = _tagHelperLocalizer.GetLocalizedText(text, TagHelper.AspFor.ModelExplorer); return("<small id=\"" + idAttr?.Value + "InfoText\" class=\"form-text text-muted\">" + localizedText + "</small>"); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.Content.SetContent("root-content"); }
protected virtual async Task <string> GetLabelAsHtmlUsingTagHelperAsync(TagHelperContext context, TagHelperOutput output, bool isCheckbox) { var labelTagHelper = new LabelTagHelper(_generator) { For = TagHelper.AspFor, ViewContext = TagHelper.ViewContext }; var attributeList = new TagHelperAttributeList(); if (isCheckbox) { attributeList.AddClass("custom-control-label"); } return(await labelTagHelper.RenderAsync(attributeList, context, _encoder, "label", TagMode.StartTagAndEndTag)); }
/// <summary> /// Called when the tag helper is being processed. /// </summary> /// <param name="context">The context within which the tag helper is processed</param> /// <param name="output">The output from the tag helper</param> public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var fc = context.GetFieldConfiguration(); if (AddClass != null) { fc.AddClass(AddClass); } if (Id != null) { fc.Id(Id); } if (InlineLabel != null) { fc.InlineLabel(InlineLabel); } if (InlineLabelHtml != null) { fc.InlineLabel(InlineLabelHtml); } if (InlineLabelHtmlContent != null) { fc.InlineLabel(InlineLabelHtmlContent); } if (Placeholder != null) { fc.Placeholder(Placeholder); } if (Rows.HasValue) { fc.Rows(Rows.Value); } if (Cols.HasValue) { fc.Cols(Cols.Value); } if (!string.IsNullOrWhiteSpace(Min)) { fc.Min(Min); } if (!string.IsNullOrWhiteSpace(Max)) { fc.Max(Max); } if (Step.HasValue) { fc.Step(Step.Value); } if (Disabled.HasValue) { fc.Disabled(Disabled.Value); } if (Readonly.HasValue) { fc.Readonly(Readonly.Value); } if (Required.HasValue) { fc.Required(Required.Value); } switch (As) { case RenderAs.CheckboxList: fc.AsCheckboxList(); break; case RenderAs.RadioList: fc.AsRadioList(); break; case RenderAs.Dropdown: fc.AsDropDown(); break; } if (!string.IsNullOrWhiteSpace(TrueLabel)) { fc.WithTrueAs(TrueLabel); } if (!string.IsNullOrWhiteSpace(FalseLabel)) { fc.WithFalseAs(FalseLabel); } if (!string.IsNullOrWhiteSpace(NoneLabel)) { fc.WithNoneAs(NoneLabel); } if (!string.IsNullOrWhiteSpace(FormatString)) { fc.WithFormatString(FormatString); } if (HideEmptyItem) { fc.HideEmptyItem(); } if (Exclude != null) { fc.Exclude(Exclude); } if (WithoutInlineLabel) { fc.WithoutInlineLabel(); } if (InlineLabelWrapsElement.HasValue) { fc.InlineLabelWrapsElement(InlineLabelWrapsElement.Value); } fc.Attrs(Attrs); return(Task.CompletedTask); }
protected virtual TagHelperAttributeList GetInputAttributes(TagHelperContext context, TagHelperOutput output) { var groupPrefix = "group-"; var tagHelperAttributes = output.Attributes.Where(a => !a.Name.StartsWith(groupPrefix)).ToList(); var attrList = new TagHelperAttributeList(); foreach (var tagHelperAttribute in tagHelperAttributes) { attrList.Add(tagHelperAttribute); } return(attrList); }
/// <summary> /// Creates the framework control. /// </summary> /// <param name="context">Contains information associated with the current HTML tag.</param> /// <param name="output">A stateful HTML element used to generate an HTML tag.</param> /// <returns>The control instance.</returns> protected override FWInputControl RenderInputControl(TagHelperContext context, TagHelperOutput output) { FWTextboxControl control = new FWTextboxControl(RequestContext, For.Model, For.Metadata); control.Attributes.Add("data-control", "textbox"); if (!string.IsNullOrWhiteSpace(Icon)) { control.Icon(Icon); } if (!string.IsNullOrWhiteSpace(Placeholder)) { control.PlaceHolder(Placeholder); } if (Autocomplete != null) { control.Autocomplete(Autocomplete, Results, ForceSelection); } return(control); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "input"; }