0

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?

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
  • Maybe you should write [your own extension](http://stackoverflow.com/questions/6660146/set-disable-attribute-based-on-a-condition-for-html-textboxfor) for this. – Johannes Egger Mar 25 '15 at 05:01
  • 5
    You would need to test each condition - e.g. `@Html.EditorFor(m => m.Description, Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })` –  Mar 25 '15 at 05:10
  • @StephenMuecke by far the most convenient answer. Why not write a proper answer? – Shimmy Weitzhandler Mar 25 '15 at 05:13
  • @Shimmy, Just showing what you could do, but its going to be rather long and messy because you have 2 conditions to check (`Model.IsReadOnly` and `Model.IsDisabled`). If this is not a 'once off' I would consider a custom helper (and do you really want to disable controls? - they wont post back). –  Mar 25 '15 at 05:17
  • @StephenMuecke, just included them for the sake of the example. Anyway, I've found an elegant solution and posted it [here](http://stackoverflow.com/a/29248004/75500), since this question is closed as a dupe. – Shimmy Weitzhandler Mar 25 '15 at 05:37

1 Answers1

1

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')
}
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69