My first MVC project and have ran into an issue which I hope someone can assist with.
Basically I have a DropDownListFor object which I want to populate with a list of available times for the user to pick from and store the selected item in an attribute for later consumption.
The below is producing a null value error so I’m missing something obvious, any help would be appreciated.
Here’s what I have:
Controller:
private MyModelObject m_model = new MyModelObject();
public ActionResult Index()
{
var AvailTimes = new SelectList(new[]
{
new {Value="00:00",Text="12:00 AM"},
new {Value="00:30",Text="12:30 AM"},
new {Value="01:00",Text="1:00 AM"},
new {Value="22:30",Text="10:30 PM"},
new {Value="23:00",Text="11:00 PM"},
new {Value="23:30",Text="11:30 PM"},
});
return View(m_model);
}
Model:
public class MyModelObject
{
public string StartTime { get; set; }
public IEnumerable<SelectList> AvailTimes { get; set; }
}
View:
@Html.DropDownListFor(model => model.StartTime,
new SelectList(model.AvailTimes, "Value", "Text"))
Don’t make your model a private variable to the controller. Each time a request is sent a new controller instance will be created so don’t think that you will be able to reuse it between actions. Also you don’t seem to be doing anything useful with the
AvailTimeslocal variable that you declared in your action and it is subject to a fast garbage collection. Also your model is incorrect. TheAvailTimesproperty must be anIEnumerable<SelectListItem>and notIEnumerable<SelectList>.Let’s start by fixing the view model first:
then the controller action which will feed the view model:
and finally the strongly typed view:
You also have the possibility to assign those available hours in your view model directly:
Now your controller action could become:
and the view obviously stays unchanged.