DropDownListFor with ASP.NET MVC

This tutorial will walk you through the details of creating a SELECT list using HtmlHelper in razor view. There are mainly two helper extension available,

  • DropDownList()
  • DropDownListFor()

We will be concentrating on the DropDownListFor extension method and its different implementation.

Generate a Select Box with Static Items

Lets assume we want to display a static list in one of the pages of our ASP.NET MVC web application, to verify the person who is accessing our application is human. I know this sounds rather silly, lets roll with it for the sake of our example !!

We want to display a drop-down list where the user will have two option to choose from;

  • Yes, I am a Human
  • No, I am a Robot

Lets say we have a model class as follows, I am gonna keep it really simple with one property:

In our view we will write the following code to display the same

This will render into following Html code:

A point to note here is that its a best practice not to create SelectList in the View itself, you should rather create it in controller and pass it to the view using ViewData.  

Lets dig right in and see how we can make use of ViewData for the same. First you need to generate the SelectList items in your controller, I have wrote a private method in my controller as below for the same.

Then in your ActionResult store the value to ViewData

Finally in our View, we will write the following code to generate the DropDownList

This will render into following Html code

You can also use VIewBag instead of ViewData, also you can get a list of item from DB and store it to ViewData to generate a DropDownList

Hope this was helpful !

Over 6 years of experience in Software Development and Front End Development. Experience in Coding, Testing, Design on Microsoft Platform Technologies, HTML/CSS, scripting etc. Area of exposure includes software development using Microsoft Asp NET, C# and SQL Server for web.

Leave a Reply

3 Comments

  1. Please don’t forget to put in your viewpage, at top:
    @model DropDown.Models.Verify (DropDown has to be changed by the namespace of your project).

    It would be great have the same example from an existing database, having a very single model like:
    books (id, Name, CategoryId)
    categories(CategoryId, CategoryName)

    So, you can register as many caterories you wish. When registering books, the select shows all categories but the table books is instantiated with CategoryId – and not CategoryName… There is no example of this simple and usefull task in all recent webpages at Internet…. Better, there are, but they don’t work…

    Thanks for your great example.

    • Glad you liked it, I will try to create another article soon with the example you mentioned. I guess you are right there is not much example for the same.

  2. Amit

    Great Code
    Thanks
    Save my day

Next ArticleSpecified Cast is not Valid : How to Backup Db from MSSQL 2012 to 2008 ?