ASP.NET MVC razor: conditional attribute in HTML

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

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

  • class=\
  • 7条回答
    •  伪装坚强ぢ
      2020-12-02 15:30

      I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true:

      public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func condition = null)
      {
          if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
          {
              return MvcHtmlString.Empty;
          }
      
          var render = condition != null ? condition() : true;
      
          return render ? 
              new MvcHtmlString(string.Format("{0}=\"{1}\"", name, HttpUtility.HtmlAttributeEncode(value))) : 
              MvcHtmlString.Empty;
      }
      

      Once defined, I can use this method in my Razor views:

    • example.isNew))> ...
    • The above code will render

    • ...
    • if example.isNew == true, if not will omit the entire class attribute.

    提交回复
    热议问题