Creating DropDownListFor items in the view

Sampat picture Sampat · Jan 2, 2012 · Viewed 11.5k times · Source

I want to create a DropDownList with a binding for one of my model data, but i want the dropdown items to be built within the View and i do not want the items coming in the Model data or from my controller. Can you please suggest how to build the selectlist within View Basically I want to create something like this:

<%= Html.DropDownListFor(model=>model.SomeProperty,<<create the dropdown list items here>> %>

Please suggest.

-Sampat.

Answer

Pankaj Upadhyay picture Pankaj Upadhyay · Jan 2, 2012

You can't use it that way. As the name suggests its for returning an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes.

Though you can create this list object in view like following :-

@Html.DropDownListFor(model => model.DropDownElement, 
                       new SelectList(model.DropDownElement, "Id", "Name"))

Update

I will take the example of a Country Model with an Id/Name pair. Like following

public class Country 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Now, in your controller action, you can pass it as a selectlist:

public ActionResult YourAction()
{
    YourModel yourModel = new YourModel(); // Just for reference. I suppose you must be passing some model to your view
    ViewBag.DropDownList = new SelectList(db.Countries, "Id", "Name"); // This way you don't need to make any changes with your passing model.
    return View(yourModel);
}

And finally in View, you can use the DropDownListFor in the following manner.

@Html.DropDownListFor(model => model.YourModelProperty, 
   (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---") 

On a Sidenote, if you just want to display a list of numbers with value, you can directly enter the HTML and utilize it, rather than using the DropDownListFor. Like follwing

<select id="yourModelPropertyName" name="yourModelPropertyName">
   <option value="">---Select Value---</option>
   <option value="1">India</option>
   <option value="2">Australia</option>
   <option value="3">US</option>
   <option value="4">England</option>
   <option value="5">Finland</option>
</select>

Just make sure that "yourModelPropertyName" is correct and it should be the one for the property where you want it updated

More update

In the views where you wan't to show the selected value, use below code

<select id="yourModelPropertyName" name="yourModelPropertyName">
   <option selected="selected" value="1">@model.YourDropDownList</option>
   <option value="2">India</option>
   <option value="3">Australia</option>
</select>

This shall do the trick :-)