I have a page where roles are displayed in the checkbox list, you can select the roles that you want the user to have, and then click the button to save it.
Here is my model:
public class RegisterModel
{
[DisplayName("Roles")]
public string[] Roles
{
get
{
return System.Web.Security.Roles.GetAllRoles();
}
set { }
}
}
My opinion:
<%@ 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>
<% } %>
And the functions from my controller:
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index", "Home");
}
return View(model);
}
When I try to view my page, I get the "Link to an object not set to an object instance" error in the foreach statement, which means Model.Roles is empty.
- Am I passing Roles correctly through my model? Or should I pass roles as ViewData through my controller action?
- If I pass roles as ViewData instead of my model, how can I access the selected elements when I submit the form so that I can call
Roles.AddUsersToRoles()?