Search code examples
c#htmlasp.net-mvcrazordisabled-input

How do I conditionally specify whether HTML input is disabled/readonly OR NOT?


Here's a sample of what I'm trying to achieve:

@Html.EditorFor(m => m.Description, 
  new { htmlAttributes = 
    new 
    {
      @class = "form-control",
      @readonly = Model.IsReadOnly,
      disabled = Model.IsDisabled
    }
  })

The problem is that the browser treats the existence of the readonly and disabled tokens without checking for their content, so when the IsReadOnly and IsDisabled properties are false, it will still show as disabled.

Is there any simple solution for that?


Solution

  • HTML :-

    @Html.EditorFor(m => m.Description, 
      new { htmlAttributes = 
        new 
        {
          @class = "form-control"
        }
    });
    

    Try using jQuery as shown :-

    if(@Json.Encode(Model.IsReadOnly))
    {
       $('#Description').attr('readonly','readonly')
    }
    
    if(@Json.Encode(Model.IsDisabled))
    {
       $('#Description').attr('disabled','disabled')
    }