How to set disabled in MVC htmlAttribute

后端 未结 8 2396
刺人心
刺人心 2020-12-30 02:06

When using an HTML Helper, what is the best method to set an attribute based on a condition. For example

<%if (Page.User.IsInRole(\"administrator\")) {%&g         


        
8条回答
  •  情书的邮戳
    2020-12-30 02:19

    Created an extension method on Object that will create a copy of the input object excluding any properties that are null, and return it all as dictionary that makes it easily used in MVC HtmlHelpers:

    public static Dictionary StripAnonymousNulls(this object attributes)
    {
       var ret = new Dictionary();
       foreach (var prop in attributes.GetType().GetProperties())
       {
          var val = prop.GetValue(attributes, null);
          if (val != null)
             ret.Add(prop.Name, val);
       }
       return ret;
    }
    

    Not sure about performance implications of reflecting through properties twice, and don't like the name of the extension method much, but it seems to do the job well ...

    new {
           @class = "contactDetails",
           disabled = Page.User.IsInRole("administrator") ? "true" : null
        }.StripAnonymousNulls()
    

提交回复
热议问题