How to set disabled attribute in html textbox in asp.net-mvc?

I am trying to dynamically set a disabled attribute in an html text box and have problems

I tried this in my opinion:

string disabledString = ""; if (SomeLogic) { disabledString = "disabled"; } Html.Textbox()...new Dictionary<string, object> { { "maxlength", 50 }, { "disabled", readOnlyState } })%> 

As you can see, I set the disabled attribute to "" or disabled, but when I test, it seems to be disabled anyway. Did I miss something?

+8
html asp.net-mvc textbox
Aug 09 '10 at 19:26
source share
3 answers

It was ugly for us, because the HTML spec is disgusting here.

Basically, in our vision code, we had this logic:

 bool isPlatformOwner = false; object disabledAttributes = new { @disabled="disabled", @readonly="readonly" }; //omitted code setting isPlatformOwner if (isPlatformOwner) { disabledAttributes = new { }; } 

Then for our controls was the following:

 <%=Html.CheckBoxFor(f => f.AddToReleaseIndicator, disabledAttributes)%> 

Anonymous types saved us here, but, as I said, this is a little ugly.

+16
Aug 09 '10 at 19:48
source share

Actually, for this you can write an Extension class for HtmlHelper, but you need to implement many overrides, so the fastest solution I found was to write a dictionary extension.

To do this, you can use the class below:

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

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

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

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

+3
May 05 '13 at 22:22
source share

I think you want to omit the disabled attribute altogether if you want it to be included. Older browsers will look at the following and disable text fields:

 <input type="text" disabled></input> 

In other words, earlier HTML = "disabled" was not necessary, so for compatibility reasons you should simply omit the attribute if you want it to display correctly. I'm not sure what will happen if you try to create a strict DOCTYPE.

+1
Aug 09 '10 at 19:31
source share



All Articles