Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate dropdownlist in asp.net MVC razor

In my razor I am generating dropdown list like this.

    @{
        var listItems = new List<ListItem> 
        { 
              new ListItem { Text = "Home To School", Value = "0" }, 
              new ListItem { Text = "School To Home", Value = "1" } 
        };
    }

@Html.DropDownList("Direction", new SelectList(listItems),new {onchange = "getAlldata()"})

HTML generated from this is like this

<select id="Direction" name="Direction" onchange="getAlldata()">
<option>Home To School</option>
<option>School To Home</option>
</select>

but I want to generate HTML something like this

<select id="Direction" name="Direction" onchange="getAlldata()">
<option value="0">Home To School</option>
<option value="1">School To Home</option>
</select>

How can I do this.

like image 762
vaibhav shah Avatar asked Apr 19 '13 07:04

vaibhav shah


People also ask

How do you bind a static value to a DropDownList in MVC?

Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.


1 Answers

Here are some examples of how to build DropDownList with Razor, like one with using SelectListItem:

public ActionResult Index()
{
  var db = new NorthwindEntities();
  IEnumerable<SelectListItem> items = db.Categories
    .Select(c => new SelectListItem
                   {
                     Value = c.CategoryID.ToString(), 
                     Text = c.CategoryName
                   });
  ViewBag.CategoryID = items;
  return View();
}

EDIT:

Check this:

@Html.DropDownList("Direction", new List<SelectListItem>
{
  new SelectListItem{ Text = "Home To School", Value = "0" },
  new SelectListItem{ Text = "School To Home", Value = "1" } 
},new {onchange = "getAlldata()"})
like image 62
Konrad Gadzina Avatar answered Oct 14 '22 18:10

Konrad Gadzina