Search code examples
htmlasp.net-mvctextbox

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


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?


Solution

  • 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:

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

    Then, for our controls, we had this:

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

    Anonymous types saved us here, but, like I said, it got a little ugly.