I find the Html helper APIs for ASP.NET MVC ackward and confusing. That’s why I like creating these little examples to figure out what is going on.
Here is a simple example of how to create a drop down list in ASP.NET MVC using Html.DropDownListFor.
You can do it like this all inlined in your *.cshtml file like so:
@Html.DropDownListFor(model => model.Package.State, new SelectList( new List<Object>{ new { value = 0 , text = "Red" }, new { value = 1 , text = "Blue" }, new { value = 2 , text = "Green"} }, "value", "text", 2))
With produces this:
<select id="Package_State" name="Package.State"><option value="0">Red</option> <option value="1">Blue</option> <option value="2">Green</option> </select>
The model => model.Package.State expression is used to generate the id and name on the select.
The string value and text matter as they need to match the model attributes of the listItem in the list.
Or you can create your own List collection (with different fields for value and text) in your controller, set it on you model, and then use in your view like this:
@Html.DropDownListFor(model => model.Package.State.Id, new SelectList( Model.PackageStates, "id", "name", Model.Package.State.Id))
Longer version
Here is a more indepth example with break down using modesl, view and controller.
Model
I basically have x3 models.
PackageState – contains the state of my package (fake domain object I made up).
Package – contains the PackageState and whatever else I want to throw in there.
DashboardIndexModel – this is how I bundle everything in the controller to send to the view.
PackageState.cs
[Serializable] public class PackageState { private PackageState(int id, string name) { this.Id = id; this.Name = name; } public int Id { get; set; } public string Name { get; set; } public static PackageState Received = new PackageState(1, "Received"); public static PackageState Processing = new PackageState(2, "Processing"); public static PackageState Complete = new PackageState(3, "Complete"); }
Package.cs
public class Package { public PackageState State { get; set; } public Package(PackageState state) { State = state; } }
DashboardIndexModel.cs
public class DashboardIndexModel { public Package Package { get; set; } public IEnumerable<SelectListItem> PackageStates { get; set; } // dropdown }
Controller
Here is where I prepare my dropdown list. I could do the work in the view (like the short example above). But here I have chosen to do it in the controller to keep the view clean and because I want to be able to set which element in my drop down should be selected.
public class DashboardController : Controller { // // GET: /Dashboard/ public ActionResult Index() { PackageRepository.Package = new Package(PackageState.Complete); IList<PackageState> states = new List<PackageState> {PackageState.Received, PackageState.Processing, PackageState.Complete}; int selectedStateId = 2; // hard code for demo IEnumerable<SelectListItem> selectList = from s in states select new SelectListItem { Selected = (s.Id == selectedStateId), Text = s.Name, Value = s.Id.ToString() }; // Do this if you don't care about selection // List<SelectListItem> selectList = states.Select(state => new SelectListItem {Value = state.Id.ToString(), Text = state.Name}).ToList(); var model = new DashboardIndexModel { Package = PackageRepository.Package, PackageStates = selectList }; return View(model); } }
View
And here is the view showing x2 ways to create the dropdown list.
Index.cshtml
@model Dashboard.Models.DashboardIndexModel @{ ViewBag.Title = "Index"; } <h2>Index</h2> <fieldset> <legend>Package</legend> <div class="display-field"> @Html.DisplayFor(model => model.Package.State.Name) </div> @Html.DropDownListFor(model => model.Package.State.Id, new SelectList( new List<Object>{ new { value = 0 , text = "Red" }, new { value = 1 , text = "Blue" }, new { value = 2 , text = "Green"} }, "value", "text", 2)) @Html.DropDownListFor(model => model.Package.State.Id, Model.PackageStates) </fieldset>
So that’s it. A simple of a dropdown. Don’t worry if you find these helpers confusing at first (I know I did at first too). But creating little experiments like this, and viewing the HTML output helps the understanding.
Links that help
http://stackoverflow.com/questions/5554421/dropdownlist-selectlist-selectedvalue-issue
http://stackoverflow.com/questions/3057873/how-to-write-a-simple-html-dropdownlistfor
http://stackoverflow.com/questions/781987/how-can-i-get-this-asp-net-mvc-selectlist-to-work
MVC.NET Html helper extension examples « The Agile Warrior
Dec 17, 2012 @ 15:45:16
Gowtham
Feb 20, 2013 @ 12:39:06
I am Getting Error in
@Html.DropDownListFor(model => model.Package.State.Id, new SelectList(
new List{
new { value = 0 , text = “Red” },
new { value = 1 , text = “Blue” },
new { value = 2 , text = “Green”}
},
“value”,
“text”,
2))
@Html.DropDownListFor(model => model.Package.State.Id, Model.PackageStates)
Abisoye Olatunji Falabi
Aug 09, 2015 @ 18:25:16
Nice article, for anyone having problems when you use the code for the view in the first part of the article i had to remove Package from the code and here is what i used for mine:
@Html.DropDownListFor(model => model.QuestionTopic, new SelectList(
new List{
new { value = 0, text = “Addition” }, new {value = 1,text = “Multiplication”}, new {value = 2, text = “Division”}},
“value”, “text”, 2))
///End of code.
Please note that QuestionTopic used in my code is the property i declared in my model.
prageethgodage
Jun 20, 2013 @ 16:47:10
Really Great article I please keep doing this kind of pattern.Thank you.
Peter Laurie
Sep 26, 2013 @ 17:56:14
Hi,
Yes great introduction to a mind-bending part of mvc. I have one issue when completeing this, I get an error with the part: PackageRepository.Package, Visual Studio error: The name ‘PackageRepository’ does not exist in the current context.
Please can you indicate what is wrong or missing. I quick reply would be fantastic as I am trying to sort out how to best display drop-down lists.
Thank you.
Pete
absl171
Oct 22, 2013 @ 07:44:14
Good article.
But it would be nice if you could explain in detail how to retrieve the id or value of the selected item.
And if possible which overloads there are and perhaps give an example..
Anisul Haque
Dec 07, 2013 @ 10:05:03
I got problem on
as
Error 1 The name ‘PackageRepository’ does not exist in the current context c:\users\anis\documents\visual studio 2012\Projects\Dashboard\Dashboard\Controllers\DashboardController.cs 19 13 Dashboard
Shailendra Yadav
Apr 26, 2014 @ 12:49:51
thanks for the article !!
John
Aug 20, 2014 @ 19:28:32
what is the “2” for at the end of the code next to “text”?
victor
Sep 16, 2014 @ 21:52:35
I need to do something and I hate MVC, ASPX is the best there is…
Thorvantes
Oct 14, 2014 @ 00:48:28
Thank you very much, this was tremendously useful.
Jose
Dec 12, 2014 @ 05:03:29
muchas gracias, busque por todo Internet de hacer la forma “fácil” y solo aquí la encontré.
Saludos desde Chile
stu
Feb 07, 2015 @ 18:12:16
your a star thanks…
nearly every other guide was to do with binding the value to model attributes but this is exactly what I was looking for
JR
Feb 08, 2015 @ 09:25:07
Good stuff. Glad it helped. Cheers.
don
Dec 16, 2015 @ 12:25:39
glad to see
chourouk
Jan 12, 2016 @ 20:05:35
https://code.msdn.microsoft.com/Dropdowlist-in-MVC5-8571a783
Missel
Mar 15, 2016 @ 03:45:16
Good example
Thank you…
Thái Hòa Huỳnh
May 30, 2016 @ 13:28:36
Thanks so much, it really useful for my project.
You don’t mind if I ask you a question that how can I binding data from my SQL Server Database to drop down list, instead of using List in View directly ?
MVC.NET Html helper extension examples | The Agile Warrior
Dec 22, 2016 @ 16:16:57
HasanAri
May 16, 2017 @ 19:15:32
Hi, I have a problem and need your help. Can you look this link an help me please. Thank you.
http://stackoverflow.com/questions/43990057/how-to-search-using-dropdownlistfor-in-mvc
rams r
Mar 01, 2019 @ 05:31:22
Thanks a lot for your article. The elaborate detailing of the model class, controller method and view really helped to piece my puzzle together.
Vikas Lalwani
Nov 20, 2020 @ 12:20:56
Good post, if anyone need more explanation on this.
You can check
https://qawithexperts.com/article/asp-net/dropdown-list-in-mvc-using-razor-htmldropdownlist-and-htmldr/254
Thanks