Approach using the TagWrap extension method. The code for your question will look like this:
@using (Html.TagWrap("li", condition ? new { @class = "active" } : null)) { var anchorAttrs = new Dictionary<string, object> { { "href", Url.Action("BusinessDetails", "Business") } }; if(condition) { anchorAttrs["style"] = "color: white; background-color: #08C; border: 1px solid #08C;"; } using (Html.TagWrap("a", anchorAttrs)) { <text>Business Details</text> } }
TagWrap Extension Methods
Using Microsoft.AspNetCore.Mvc.ViewFeatures
public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, object data) { return htmlHelper.TagWrap(tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(data)); } public static IDisposable TagWrap(this IHtmlHelper htmlHelper, string tagName, IDictionary<string, object> data) { var tag = new TagBuilder(tagName); tag.MergeAttributes(data); htmlHelper.ViewContext.Writer.Write(tag.RenderStartTag()); return new DisposableAction(() => htmlHelper.ViewContext.Writer.Write(tag.RenderEndTag())); }
Helper class used to render the closing tag on Dispose
public class DisposableAction : IDisposable { private readonly Action DisposeAction; public DisposableAction(Action action) { DisposeAction = action; } public void Dispose() { DisposeAction(); } }
Pavlo Neyman Jul 10 '18 at 6:31 2018-07-10 06:31
source share