Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable & Specify default selection for Html.DropDownList

i am working on an asp.net mvc web application, inside the action method i define the following select list:-

ViewBag.ApproverID = new SelectList(db.staffs.ToList(), "ApproverID", "Name");

Then on the view i am trying to disable the dropdownlist as follow:-

@Html.DropDownList("ApproverID",String.Empty,new { @disabled = "disabled" } )

but seems the dropdownlist does not allow this and will raise syntax error on the view?can anyone adivce ? Thanks

like image 837
John John Avatar asked Mar 23 '26 10:03

John John


1 Answers

Your using the wrong overload of DropDownList. It would need to be

@Html.DropDownList("ApproverID", null, string.Empty, new { disabled= "disabled" })

However you should be using strongly typed helpers and binding to a model property so it can be bound on postback

Model

public int ApproverID { get; set; }

Controller

ViewBag.ApproverList = new SelectList(db.staffs.ToList(), "ApproverID", "Name");

View

@Html.DropDownListFor(m => m.ApproverID, (SelectList)ViewBag.ApproverList, "-Please select-", new { disabled = "disabled" })

If you set the value of property ApproverID in the controller and it matches one of the values of the options it will be selected.

But why disable a dropdownlist? - You obviously cant select anything and it wont post back so the model property will be null (and probably result in a ModelState error). If you are just wanting to display the value, use @Html.DisplayFor() and @Html.HiddenFor(m => m.ApproverID) so the value posts back


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!