我有一刻。我似乎无法将ListBox
中的选定项目绑定到处理post
事件的操作方法的参数中。
Model
的类型为SystemRoleList
:
public class SystemRoleList {
public IEnumerable<SystemRole> List { get; set; }
}
SystemRole
定义为:
public class SystemRole {
public Int32 Id { get; set; }
public String Name { get; set; }
}
此代码生成ListBox
:
<%: this.Html.ListBox("Roles", new SelectList(Model.List, "Id", "Name")) %>
接收所选项目的操作方法设置如下:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateSystemRoles(Int32[] roles) {
// do something with the results....
}
问题是roles
总是null
。我尝试过使用其他数据类型 - string[]
,ICollection<int>
等。如果我Request.Form
,我可以在Request.Form["Roles[]"]
集合中看到这些值。如果我从1,3,4
选择了这些项目,则典型值可能为ListBox
。
如何命名ListBox
或我的参数,以便MVC自动绑定值?
答案 0 :(得分:1)
很奇怪,以下对我来说非常好。
型号:
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>