Razor DropDownList Not Disabling

2019-09-11 23:45发布

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)

3条回答
男人必须洒脱
2楼-- · 2019-09-12 00:06

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

查看更多
唯我独甜
3楼-- · 2019-09-12 00:17

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)
查看更多
霸刀☆藐视天下
4楼-- · 2019-09-12 00:26

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

查看更多
登录 后发表回答