Странно, у меня прекрасно работает следующее.
Модель:
public class SystemRoleList
{
public IEnumerable<SystemRole> List { get; set; }
}
public class SystemRole
{
public int Id { get; set; }
public string Name { get; set; }
}
Контроллер:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new SystemRoleList
{
List = new[]
{
new SystemRole { Id = 1, Name = "role 1" },
new SystemRole { Id = 2, Name = "role 2" },
new SystemRole { Id = 3, Name = "role 3" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(int[] roles)
{
return Content("thanks for submitting");
}
}
Вид:
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Controllers.SystemRoleList>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.ListBox("Roles", new SelectList(Model.List, "Id", "Name")) %>
<button type="submit">OK</button>
<% } %>
</asp:Content>
При этом я буду использовать строго типизированную версию помощника ListBox
, например:
Модель:
public class SystemRoleList
{
public int[] Roles { get; set; }
public IEnumerable<SystemRole> List { get; set; }
}
Контроллер:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new SystemRoleList
{
List = new[]
{
new SystemRole { Id = 1, Name = "role 1" },
new SystemRole { Id = 2, Name = "role 2" },
new SystemRole { Id = 3, Name = "role 3" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(SystemRoleList model)
{
return Content("thanks for submitting");
}
}
Вид:
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Controllers.SystemRoleList>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.ListBoxFor(x => x., new SelectList(Model.List, "Id", "Name")) %>
<button type="submit">OK</button>
<% } %>
</asp:Content>