SelectList within a foreach loop
I have the following code in a controller:
public static IEnumerable<SelectListItem> EventStatus = new[] {
new SelectListItem{ Text=Active, Value=Active},
new SelectListItem{ Text=CheckedIn, Value=CheckedIn},
new SelectListItem{ Text=Inactive, Value=Inactive}
};
ViewData["EventStatus"] = EventStatus;
I'm trying to iterate through a foreach loop in an .aspx file and binding the value to the SelectList.
<% foreach (var item in Model) { %>
....
<%= Html.DropDownList("item.Status", ViewData["EventStatus"] as SelectList)%>
...
This isn't working. I'm getting:
There is no ViewData item with the key 'item.Status' of type 'IEnumerable'.开发者_C百科
but <%= Html.Encode(item.Status) %>
works.
I also tried this:
<%= Html.DropDownList("item.Status", (IEnumerable<SelectListItem>)ViewData["EventStatus"])%>
This displays the list, but nothing is selected (no binding occurs).
Anyone have any suggestions?
Cheers,
Dean
You do not have to loop through to bind item to a control like DropDownList or ListBox just do this
<%= Html.DropDownList("ControlName", ViewData["EventStatus"] as IEnumerable<SelectListItem>)%>
for DropDownList and like this
<%= Html.ListBox("ControlName", ViewData["EventStatus"] as IEnumerable<SelectListItem>)%>
for ListBox
I would recommend you to use view models instead of ViewData. This way your views will be strongly typed. For example you could have the following view model:
public class MyViewModel
{
public string Status { get; set; }
public IEnumerable<SelectListItem> EventStatuses
{
get
{
return new SelectList(new[]
{
new SelectListItem{ Text = Active, Value = Active },
new SelectListItem{ Text = CheckedIn, Value = CheckedIn },
new SelectListItem{ Text = Inactive, Value = Inactive }
}, "Value", "Text");
}
}
}
and then in your controller:
public class HomeController: Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO: Do something with the selected model.Status
return View(model);
}
}
and finally the strongly typed view:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.Status, Model.EventStatuses) %>
<input type="submit" value="OK" />
<% } %>
Can you post a bit more of your controller. What you have shown wouldn't build, is it actual source or did u type it in?
It looks like when the view is executing ViewData["EventStatus"] is null. If you put:
<%= ViewData["EventStatus"] == null %>
in your view does it come up true or false?
From Mvc2 Source (SelectExtensions.SelectInternal):
if (selectList == null) {
selectList = htmlHelper.GetSelectData(name);
usedViewData = true;
}
selectList is the list that was passed in. As you can see if it is null it attempts to get a value from the view data using the "name" (which in this case is "item.Status").
精彩评论