how do I set disabled attribute on html textbox in asp.net-mvc?

前端 未结 3 653
走了就别回头了
走了就别回头了 2021-01-05 05:12

I am trying to dynamically set the disabled attribute on the html textbox and having issues

I tried this in my view:

 string disabledString = \"\";
          


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 05:58

    Actually it is possible to write an Extension class to the HtmlHelper to do this but you have to implement many overrides so the quickest solution I found was to write a dictionary extension.

    You can use below class for this:

    public static class DictionaryExtensions
    {
        public static Dictionary WithAttrIf(this Dictionary dictionary,bool condition, string attrname, object value)
        {
            if (condition)
                dictionary[attrname] = value;
    
            return dictionary;
        }
    
        public static Dictionary WithAttr(this Dictionary dictionary, string attrname, object value)
        {
    
            dictionary[attrname] = value;
    
            return dictionary;
        }
    }
    

    To use it, import the class in your view and your view code looks like this:

    @Html.TextBoxFor(m => m.FirstName,  new Dictionary().WithAttr("class","input-large").WithAttrIf(!string.IsNullOrWhiteSpace(Model.FirstName),"readonly","yes"))
    

    You can add as many attributes as you wish since the extension method adds the value to the dictionary and returns the dictionary itself

提交回复
热议问题