Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2 - How do I use DropDownListFor?

I have a simple model / view with things like Username, Password etc. and use helpers fine to hook it up.

I now have a field called "NumberOfChildren". I want to store a number in it (int) and I want it render a dropdown box containing "None", "1", "2" etc.

My thoughts would be that the model would have a list or a method that returns a list, so I can specify the values such as NumberOfChildren_List that I put the data into, and then DropDownListFor pulls that list and renders it, matching the value to the value of the item in the dropdown.

However after spending about 30 minutes on trying to figure out how on earth it works, I gave up and decided to ask here. Any ideas?

Edit: Here's some code...

<%: Html.DropDownListFor(m => m.NumberOfChildren, new SelectList(Model.NumberOfChildrenListValues))%>

and in the model

        [Required]
        [DisplayName("How many children do you have?")]
        public string NumberOfChildren { get; set; }

        public IEnumerable<string> NumberOfChildrenListValues
        {
            get
            {
                List<string> list = new List<string>() { "None", "1", "2" };

                return list;
            }

            set
            {

            }

        }

I get an object not set to instance of object error though. Ideas?

like image 438
NibblyPig Avatar asked Nov 06 '22 12:11

NibblyPig


1 Answers

Try like this (you need to set the text and the value for each option - the text will be used for rendering in the dropdown list and the value will be used to bind to the selected item to the NumberOfChildren property):

[Required]
[DisplayName("How many children do you have?")]
public string NumberOfChildren { get; set; }

public IEnumerable<SelectListItem> NumberOfChildrenListValues
{
    get
    {
        return new[]
        {
            new SelectListItem { Value = "0", Text = "None" },
            new SelectListItem { Value = "1", Text = "1" },
            new SelectListItem { Value = "2", Text = "2" },
        };
    }
}

and then:

<%: Html.DropDownListFor(
    m => m.NumberOfChildren, 
    Model.NumberOfChildrenListValues
) %>
like image 170
Darin Dimitrov Avatar answered Nov 11 '22 15:11

Darin Dimitrov