Подход с методом расширения TagWrap. Код для вашего вопроса будет выглядеть так:
@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
с использованием 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()));
}
Вспомогательный класс, используемый для рендеринга закрывающего тега при Dispose
public class DisposableAction : IDisposable
{
private readonly Action DisposeAction;
public DisposableAction(Action action)
{
DisposeAction = action;
}
public void Dispose()
{
DisposeAction();
}
}