我有一个角色显示在复选框列表中的页面,您可以选择用户想要的角色,然后单击一个按钮进行保存它。MVC:在复选框列表中显示角色,然后保存它们
这里是我的模型:
public class RegisterModel
{
[DisplayName("Roles")]
public string[] Roles
{
get
{
return System.Web.Security.Roles.GetAllRoles();
}
set { }
}
}
我的观点:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<WebUI.Models.RegisterModel>" %>
<% using (Html.BeginForm()) { %>
<% foreach(string role in Model.Roles) { %>
<input type="checkbox" value="<%: role %>" /> <%: role %>
<% } %>
<p>
<input type="submit" value="Register" />
</p>
<% } %>
而且从我的控制器的功能:
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
//save roles
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View(model);
}
当我尝试查看我的网页,我得到一个foreach语句中的“对象引用未设置为对象的实例”错误,表示Model.Roles为空。
- 我是否通过我的模型正确地传递角色?还是应该通过我的Controller动作将角色作为ViewData传递?
- 如果我将角色作为ViewData传递而不是通过我的模型传递,那么当我提交表单时如何才能访问所选项目,以便我可以调用
Roles.AddUsersToRoles()
?