Freelance Web Development in Malta


ASP.NET MVC 4 ViewBag and Dropdownlists

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta,a small island in the Mediterranean. So now let me start this blog post :) .

The outcomes of this blog are to

  1. Discover what is the ViewBag and how this can be used to return data back to a View
  2. Use a DropdownList to display data for a foreign key column

The prerequisites to follow this blog are

  1. You should have SQL Server Express installed. You can install it from here
  2. You should have two tables Products and Categories inside your database
  3. You should have some understanding of LINQ To Entities

This blog will explain how you can give the opportunity to a user to select a Product Category from a dropdown list, for a specific Product. In the previous blog we saw how the user had to input the CategoryId manually. This, of course, is not the ideal situation since the user would have to remember all the ids for all the Product Categories manually.

So basically, the first thing we should be doing is to create a method which returns all Product Categories from our database. This method should be included in our business class which is included in our Models folder. This code is shown underneath.

/// <summary>
 /// Gets all product categories
 /// </summary>
 /// <returns>All product categories.</returns>
 public IQueryable<Category> GetCategories()
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 return entities.Categories;

Once we are finished from our business method we need to call this method from our controller method. Basically, this information should be displayed in our ASP.NET MVC View, using a DropdownList. To display this information we need to make use of the SelectListItem which represents one single dropdown option made up of the Text and the Value. The Text property is the text which the user sees in the dropdown whilst the Value is the value stored for the option selected.

Let’s assume we wish to include our DropdownList inside the Create controller method, which basically serves as the controller which adds a new product.  The underneath code is the code snippet inside our controller method which basically creates a List of SelectListItems. For each SelectListItem we are setting its Value to the CategoryId, whilst we are setting its Text to the CategoryName. This would mean that we will be storing the CategoryId inside the ProductCategory foreign key whilst displaying the CategoryName.

public ActionResult Create()
 List<SelectListItem> Categories = (from p in
 new Models.DBProducts().GetCategories().ToList()
 select new SelectListItem()
 Value = p.CategoryId.ToString(),
 Text = p.CategoryName
ViewBag.ProductCategory = Categories;
 return View();

On line 11 I will then make use of the ViewBag which is a special object to pass the List of all SelectListItems back to the respective View. The ViewBag is no more than a container of objects which can then be accessed from the ASP.NET MVC View. You can place any object in the ViewBag and then access it using from the MVC View. We are naming the ViewBag variable ProductCategory so that it would have the same name as our ProductCategory field which can be found in the Products table. Recall that in our previous blog we ensured that the fields, found inside our ASP.NET MVC view, had the same names as the table’s fields found in our database. This will enable ASP.NET MVC to map the field values to their relevant database column fields.

Now let’s concentrate on how we will display the DropdownList in our ASP.NET MVC View. This can be done by using the DropDownList helper as shown in the underneath code. You should ensure that the name given is the same as the name given in the ViewBag found in our controller method.


If you run your ASP.NET MVC application and navigate to the Create Product controller method you should end up with a page like the one shown in Figure 1.

Figure 1 - Dropdownlist in View

Figure 1 – How the DropDownList will be shown in your ASP.NET MVC View

The actual HTML which is created is then shown underneath.

<select id="ProductCategory" name="ProductCategory"><option value="1">Motherboards</option>
<option value="2">CPU</option>

Note that each Category SelectListItem we have created in our Controller is represented by an HTML Option. We are storing the CategoryId as the Value whilst we are showing the CategoryName back to the user.

I hope that you found this blog interesting and that you have learned how to use DropdownLists in ASP.NET MVC.

14 comments on “ASP.NET MVC 4 ViewBag and Dropdownlists

  1. Krasimir on said:

    what is Categories in this method

    public IQueryable GetCategories()
    Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
    return entities.Categories;

    • admin on said:

      The Categories is a table inside SQL Server which is then available through LINQ To Entities Model.

      So basically if you create a table called Categories inside your SQL Server database, and then you create a LINQ To Entities model for your database you will be able to see the Categories class.

  2. Hello Sir,
    I understand your code for binding DDL in MVC.


  3. Thanks for this very simple and perfect explanation!

  4. Chandran on said:

    Hello sir,

    i am beginner in mvc, i want to db values add in dropdownlist and get selected value for insert data to db example for model class having designation variable,control class collect value through IEnumerable
    what i do?

  5. I want to display actual name from this select list in the view. Any suggestions?

    • In all honesty I do this through a JQuery method and I do the following.

      var name = $(this).text();
      //display name somewhere

  6. Ravz on said:

    Hi there… I have created a database, I have added the values to a drop drown list. I want to compare the name from the drop down list to the name in the database in order to a calcualte a price…

  7. siraj ahmed on said:


    Thank you for the blog, its really informative.
    I am facing a real time scenario, where in I need to get the selected value of a dropdown list in my view, and pass it back to controller where in I have a method to save back all the values returned from view into data base table. How do I do it, I tried many approaches but nothing has worked so far….

    • admin on said:

      Name the dropdown list the same as one of the variable controller name and the value of the dropdownlist will be passed to the controller. An example is shown underneath

      public AcionResult Save(string Town)


Leave a Reply

Your email address will not be published. Required fields are marked *


HTML tags are not allowed.