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

3

7

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?

Seda answered 6/8, 2013 at 13:4 Comment(4)
aspnetmvcninja.com/views/asp-net-mvc-select-list-exampleAdrenaline
asp.net/mvc/tutorials/javascript/…Anathematize
Refer to #782487 for some examples.Coriecorilla
This is a very pertinent question for ASP.NET MVC. 'What's this thing in c#'? It's not asking to find a tool, library, or favourite off-site resource. I had the same question and found the answers here very useful!Socalled
P
7

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)
Perichondrium answered 6/8, 2013 at 13:11 Comment(2)
Thanks, do you mean that dropdownItems is much the same as an object of type SelectList? Also, most of the answers & comments dont actually mention selectList class - does this mean that it is not used much and I normally you would just use a List of selectListItem?Seda
Yes, SelectListItem is type of System.Web.Mvc.SelectList.Perichondrium
T
3

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.

Triune answered 6/8, 2013 at 13:18 Comment(0)
E
1

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

Eastlake answered 6/8, 2013 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.