Question

I'm trying to understand c# ASP.NET MVC4 and keep coming across SelectList. I can't seem to find an explanation of what it is, other that this:

http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx

Can anyone give a simple explanation of it, and show how to use it?

Was it helpful?

Solution

There is a simple code that I used for dropdownlist in asp.net mvc:

In Controller:

   List<SelectListItem> dropdownItems = new List<SelectListItem>();
   dropdownItems.AddRange(new[]{
                            new SelectListItem() { Text = "Option One", Value = "1" },
                            new SelectListItem() { Text = "Option Two", Value = "2" },
                            new SelectListItem() { Text = "Option Three", Value = "3" }});
   ViewData.Add("DropDownItems", dropdownItems);

And, in cshtml view:

@Html.DropDownList("Types", ViewData["DropDownItems"] as List<SelectListItem>)
@Html.ValidationMessageFor(model => model.Types)

OTHER TIPS

SelectList class which contains the Key, Value pair with the Selected item to True.

For Example,

listItems.Add(new SelectListItem
                {
                    Text = xElement.Element("text").Value,
                    Value = xElement.Element("value").Value
                });

var selected = listItems.Where(x => x.Value == "Test1").First();
selected.Selected = true;

This sample which helps to get the selected value in dropdownlist.

Working with drop-down lists in ASP.NET MVC has some confusing aspects, it's the reason that you find some classes that help developers to work with this prevalent object.

There is a great blog-post which I think describes SelectList clearly.

http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top