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?

5
  • Maybe you should write your own extension for this. Commented Mar 25, 2015 at 5:01
  • 5
    You would need to test each condition - e.g. @Html.EditorFor(m => m.Description, Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { }) Commented Mar 25, 2015 at 5:10
  • @StephenMuecke by far the most convenient answer. Why not write a proper answer? Commented Mar 25, 2015 at 5: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). Commented Mar 25, 2015 at 5:17
  • @StephenMuecke, just included them for the sake of the example. Anyway, I've found an elegant solution and posted it here, since this question is closed as a dupe. Commented Mar 25, 2015 at 5:37

1 Answer 1

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')
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.