drop down list in MVC


April 2019


0 time


I am absolutely new to the MVC application.I want a dropdown list on my form I have done it this way

"<%= Html.DropDownList("Categories", (IEnumerable<SelectListItem>)ViewData["Categories"])%>"

I am sending the viewdata[Categories] from the controller class file.

this way

IList allCategories = _dropdownProvider.GetAllCategories();
ViewData["Categories"] = new SelectList(allCategories, "catid", "catname");

Now my requirement is that when the user selects a particular category from the dropdownlist its id should get inserted in the database, The main problem is category id I want to insert the category id in the product table where the category Id is the foreign Key.

Please tell me how can I do this.

3 answers


when you try to post the view, you'll have a "Categories" key in your querystring. you could convert it to long or the type you use in your table and set it to the product instance that you want to.

if this is not so clear, please send your code for a better explanation.


If i Understand right your question, the only thing you have to do, is inspect the POST for the "Categories" Key, and it will contain the selected value of the DropDownList.

var selectValue = System.Convert.ToInt16(Request.Form["name"]);

Or if you use ModelBinder and define a model that bind that value directly, you just have to Update the Model with

bool x = TryUpdateModel(YourModelNameHere);

This will automatically inspect the current Controller´s Value Provider and bind that value to the corresponding property in your model.

I recoment you to use the parameter FormCollection in your controller, and put a breakpoint, you can see all the values send within the POST. All that values are accessible through Request.Form["KEY"].


Normally you would do the following:-

On your view you would have...

Inherits="System.Web.Mvc.ViewPage<Product>" THIS IS A REFERENCE TO YOUR PRODUCT ENTITY

and in the page you can do this...

Category <%=Html.DropDownList("CatId") %>

you would also have the GET controller which defines the list

public ActionResult Add()
    ViewData["CatId"] = new SelectList(allCategories, "catid", "catname");

then you can get the CatId from the product passed in to the Add method


public ActionResult Add(Product product)
  int catId = product.CatId

HTH. You ought to buy a book on the subject as MVC takes away alot of the pain of binding from you.