Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the SelectList class in c#? [closed]

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?

like image 686
spiderplant0 Avatar asked Aug 06 '13 13:08

spiderplant0


3 Answers

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)
like image 89
Mojtaba Avatar answered Nov 10 '22 04:11

Mojtaba


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.

like image 40
Selva Avatar answered Nov 10 '22 02:11

Selva


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

like image 1
Abbas Amiri Avatar answered Nov 10 '22 03:11

Abbas Amiri