I am trying to dynamically set the disabled attribute on the html textbox and having issues
I tried this in my view:
string disabledString = "";
if (SomeLogic)
{
disabledString = "disabled";
}
Html.Textbox()...new Dictionary<string, object> { { "maxlength", 50 }, { "disabled", readOnlyState } })%>
As you can see I am setting the disabled attribute to "" or disabled but when I test, it seems to be disabled in either case. Am I missing something?
I think you want to omit the disabled attribute altogether when you want it to be enabled. Older browsers would look at the following and disable the text boxes:
In other words in older HTML the ="disabled" was not necessary so for compatibility reasons you should just omit the attribute if you want it to render right. I'm not sure what happens if you try a strict DOCTYPE, though.
This was ugly for us, due to the fact that the HTML spec is lousy here.
Basically in our view code we had some logic like this:
Then, for our controls, we had this:
Anonymous types saved us here, but, like I said, it got a little ugly.
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:
To use it, import the class in your view and your view code looks like this:
You can add as many attributes as you wish since the extension method adds the value to the dictionary and returns the dictionary itself