ASP.NET MVC 2 - How do I use DropDownListFor ?
- by SLC
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?