Introduction
In this article, We will discuss on how to create a dropdownlist in mvc projects.
Let’s Start
Story starts like this, we have a real world situation to solve.It looks like below.
A simple form to add new stock into warehouse. It consists of a product Dropdownlist, count text box and a submit button.
A database with product and stock table is given.
Hint:
Product table already populated with some products.we want these products in our dropdownlist. Stock table is empty. After form submission, productid of selected product and count from textbox will be added to stock table.
Step 1
Create fresh mvc project.
Step 2
Added ADO. NET Entity model for the DataBase as DbModel.edmx into Model folder and saved connection string as DbModels.
Product model class
1 2 3 4 5 | public partial class Product { public int ProductID { get; set; } public string ProductName { get; set; } } |
Additional ProductCollection property is added to Stock model. we will be using this property for implementing the product Dropdownlist.
1 2 3 4 5 6 7 8 9 10 | public partial class Stock { public int StockID { get; set; } [DisplayName("Product")] public int ProductID { get; set; } public int Count { get; set; } [NotMapped] public List<Product> ProductCollection { get; set; } } |
Step 3
Add Stock controller with an action AddOrEdit like below.
1 2 3 4 5 6 7 8 | [HttpGet] public ActionResult AddOrEdit(int id=0) { Stock stockModel = new Stock(); using (DbModels db = new DbModels()) stockModel.ProductCollection = db.Products.ToList<Product>(); return View(stockModel); } |
Step 4
Create AddOrEdit view, for that right click on the action click on add view. in the next window uncheck layout option.
Now we need to design the form. You can use bootstrap for designing view but I use html table for simplicity.
Define model as first line in the view
1 | @model DropDownListInMVC.Models.Stock |
Now inside the body, form design can be done like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | @using (Html.BeginForm("AddOrEdit", "Stock", FormMethod.Post)) { <table> <tr> <td></td> <td style="text-decoration:underline">Add Stock</td> </tr> <tr> <td>@Html.DisplayNameFor(model => model.ProductID)</td> <td> @Html.DropDownListFor(model => model.ProductID, new SelectList(Model.ProductCollection,"ProductID", "ProductName"), "Select") </td> </tr> <tr> <td>@Html.DisplayNameFor(model => model.Count)</td> <td>@Html.EditorFor(model => model.Count)</td> </tr> <tr> <td></td> <td><input type="submit" value="Submit" /></td> </tr> </table> } |
I don’t know whether you noticed or not we have given form action as AddOrEdit,
1 | @using (Html.BeginForm("AddOrEdit", "Stock", FormMethod.Post)) |
So we need HttpPost Action AddOrEdit. where we need to save posted data from the form.
1 2 3 4 5 6 7 | [HttpPost] public ActionResult AddOrEdit(Stock stock) { //save productId and count //code not given return View(); } |
Put a Breakpoint in this post Action.Navigate to Stock/AddOrEdit then submit the form with some test data.
After submitting the form you can check our Breakpoint.
So Selected ‘NoteBook’ id 3 and Count 10 is posted to server.after saving them our stock table looks like this.
Now let me update AddOrEdit Get Action like this
1 2 3 4 5 6 7 8 9 10 11 12 13 | [HttpGet] public ActionResult AddOrEdit(int id = 0) { Stock stockModel = new Stock(); using (DbModels db = new DbModels()) { if (id != 0) //fill stock model with corresponding StockID stockModel = db.Stocks.Where(x => x.StockID == id).FirstOrDefault(); stockModel.ProductCollection = db.Products.ToList<Product>(); } return View(stockModel); } |
Now navigate to Stock/AddOrEdit/1. you can see the same form that we posted. So now you add can functions like Update Or Delete the Stock.
Other Ways to Create DropDown List in MVC
From a hard coded list / Static List
Method-1
1 2 3 4 | stockModel.ProductCollection = new List<Product>() { new Product(){ProductID=1,ProductName="Computer"}, new Product(){ProductID=2,ProductName="Mobile Phone"}, }; |
you can use same razor code for dropdown list.
1 2 | @Html.DropDownListFor(model => model.ProductID, new SelectList(Model.ProductCollection,"ProductID", "ProductName"),"Select") |
Method-2
1 2 3 4 | ViewBag.ProductCollection = new List<SelectListItem>(){ new SelectListItem(){Value="1",Text="Computer"}, new SelectListItem(){Value="2",Text="Mobile Phone"} }; |
slight change in razor view
1 | @Html.DropDownListFor(model => model.ProductID, (List<SelectListItem>)ViewBag.ProductCollection, "Select") |
DropDownList Vs DropDownListFor
Both of them are Html Helper Methods to create dropdown list in mvc,First Parameter for these functions determines the name for dropdown list.
If we use DropDownList instead of DropDownListFor, Razor code will look like this
1 2 | @Html.DropDownList("ProductID", new SelectList(Model.ProductCollection,"ProductID", "ProductName"),"Select") |
here we need to pass name of control as magic string or name is hard coded here.
If we change Model Property ProductId to something else,during form submission, selected value of dropdown will not bind in post request.
So try to stick with DropDownListFor Method. it will make our dropdown strongly typed.
Plugin For DropDown List
There are plenty of plugins for dropdown list.
Wit attractive features like
- Search options from dropdown
- Allow multiple selection
- and much more
Popular Plugins
Post A Reply