What option do I need to set to make a drop down box readonly when using MVCs Html.DropDownList?
I\'ve tried things like....
Html.DropDownList(\"Type
Put this in style
select[readonly] option, select[readonly] optgroup {
display: none;
}
I've create this answer after referring above all comments & answers. This will resolve the dropdown population error even it get disabled.
Step 01
Html.DropDownList("Types", Model.Types, new {@readonly="readonly"})
Step 02 This is css pointerevent remove code.
<style type="text/css">
#Types {
pointer-events:none;
}
</style>
Tested & Proven
I just do this and call it a day
Model.Id > -1 ? Html.EnumDropDownListFor(m => m.Property, new { disabled = "disabled" }) : Html.EnumDropDownListFor(m => m.Property)
Regarding the catch 22:
If we use @disabled
, the field is not sent to the action (Mamoud)
And if we use @readonly
, the drop down bug still lets you change the value
Workaround: use @disabled
, and add the field hidden after the drop down:
@Html.HiddenFor(model => model.xxxxxxxx)
Then it is truly disabled, and sent to the to the action too.
try with @disabled and jquery, in that way you can get the value on the Controller.
Html.DropDownList("Types", Model.Types, new {@class = "your_class disabled", @disabled= "disabled" })
Add a class called "disabled" so you can enabled by searching that class(in case of multiples disabled fields), then you can use a "setTimeout" in case of not entering controller by validation attributes
<script>
function clickSubmit() {
$("select.disabled").attr("disabled", false);
setTimeout(function () {
$("select.disabled").attr("disabled", true);
}, 500);
}
</script>
submit button like this.
<button type="submit" value="Submit" onclick="clickSubmit();">Save</button>
in case of inputs, just use @readonly="readonly"
@Html.TextBoxFor("Types",Model.Types, new { @class = "form-control", @readonly= "readonly" })
A tip that may be obvious to some but not others..
If you're using the HTML Helper based on DropDownListFor
then your ID will be duplicated in the HiddenFor
input. Therefore, you'll have duplicate IDs which is invalid in HTML and if you're using javascript to populate the HiddenFor
and DropDownList
then you'll have a problem.
The solution is to manually set the ID property in the htmlattributes array...
@Html.HiddenFor(model => model.Entity)
@Html.EnumDropDownListFor(
model => model.Entity,
new {
@class = "form-control sharp",
onchange = "",
id =` "EntityDD",
disabled = "disabled"
}
)