ASP.NET MVC razor: conditional attribute in HTML

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

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

  • class=\
  • 7条回答
    •  余生分开走
      2020-12-02 15:31

      Based on defrosts answer here an adaptation, taking an object instead of a string:

          public static MvcHtmlString ConditionalAttr(this HtmlHelper helper, string attributeName, object value, Func condition)
          {
              if (string.IsNullOrEmpty(attributeName) || value == null)
              {
                  return MvcHtmlString.Empty;
              }
      
              var render = condition != null ? condition() : true;
      
              return render ? 
                  new MvcHtmlString($"{attributeName}=\"{HttpUtility.HtmlAttributeEncode(value.ToString())}\"") : 
                  MvcHtmlString.Empty;
          }
      

      This way you don't have to turn your other datatypes in strings before passing them, saving a fiew .ToString(). There is a difference tho: passing an empty string will still render. As example:

      @Html.ConditionalAttr("data-foo", "", () => Model.IsFooNeeded)
      
      // Ouput:
      data-foo=""
      

    提交回复
    热议问题