ASP.NET MVC razor: conditional attribute in HTML

后端 未结 7 1660
鱼传尺愫
鱼传尺愫 2020-12-02 15:21

Code below doesn\'t seems clean. Any suggestion to improve the code?

  • class=\
  • 相关标签:
    7条回答
    • 2020-12-02 15:44

      Approach with TagWrap extension method. Code for your question would 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 for rendering closing tag on Dispose

      public class DisposableAction : IDisposable
      {
          private readonly Action DisposeAction;
      
          public DisposableAction(Action action)
          {
              DisposeAction = action;
          }
      
          public void Dispose()
          {
              DisposeAction();
          }
      }
      
      0 讨论(0)
    提交回复
    热议问题