0

I have a SelectList that populates / works ok.

I have a new Requirement to disable the list for certain users. So I added in a new property to the ViewModel, LockSelectList. this property is set in the controller (and works).

However, when the list is rendered, it is always disabled.

I have tried

@Html.DropDownListFor(x => x.Id,  Model.AllLocations, new {disabled = Model.LockLocationList? "true" : "false" })

@Html.DropDownListFor(x => x.Id,  Model.AllLocations, new {disabled = Model.LockLocationList? "disabled" : "false" })

@Html.DropDownListFor(x => x.Id,  Model.AllLocations, new {disabled = Model.LockLocationList? "disabled" : "" })

but none work. they all render correct html, but it seems that the presence of the disabled attribute, no matter the value disables the list. So what do I tweak to the code make this work? (Preferably without using jQuery to handle the enable / disable after the event)

Matt
  • 1,596
  • 2
  • 18
  • 32
  • What is the point of a disabled ` –  Jan 17 '17 at 21:51
  • Because then the form will be inconsistent between users (Not my decision here!) – Matt Jan 19 '17 at 08:17
  • What do you mean inconsistent? (you can style the rendered text value to look like a form control is you want) –  Jan 19 '17 at 08:19
  • A drop down list looks different to a text box (Like I said, I think its taking the whole UI thing a bit far, considering the audience of the site, but that's not my call!) – Matt Jan 20 '17 at 09:42

3 Answers3

4

I would recommend to do it following way...

@if(Model.LockLocationList)
{
      @Html.DropDownListFor(x => x.Id,  Model.AllLocations, new {disabled = "disabled" })
}else
{
      @Html.DropDownListFor(x => x.Id,  Model.AllLocations)
}

OR you can refer following post to add it conditionally as per your choice.

Conditional disable input

Community
  • 1
  • 1
K D
  • 5,889
  • 1
  • 23
  • 35
1

Or you can do this as below if condition is true make an object which contains disable attribute else blank object. I hope it'll help you

@Html.DropDownList(x => x.Id,  Model.AllLocations, Model.LockLocationList == true ? new { @disabled = "disabled" } as object : new {} as object)
Curiousdev
  • 5,668
  • 3
  • 24
  • 38
0

Whenever the disabled attribute is present on the dropdown list, it is disabled not matter the value. So when it's not supposed to be disabled, you need to not set it at all.

See K D's answer for a code example

Hykalos
  • 51
  • 2
  • 11