Mrlondon7100
Mrlondon7100

Reputation: 75

Multiple roles in Asp.net MVC3

I have an admin site for the admin to create users. Here he has to chose the roles for the user - like the Asp.NET configuration site. I made 3 checkboxes with different roles.

[Authorize(Roles = "Admin")]
    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {

            var Rolemodel = model.RolesContainer; 
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
        }


        // If we got this far, something failed, redisplay form
        return View(model);
    }


   [Authorize(Roles = "Admin")]
    public ActionResult Register()
    {
        List<SelectListItem> tempRoles = new List<SelectListItem>();
        tempRoles.Add(new SelectListItem{ Text = "Admin", Selected = false, Value = "Admin" });
            tempRoles.Add(new SelectListItem{ Text = "Production", Selected = false, Value = "Production"});
                tempRoles.Add(new SelectListItem{ Text = "Sale", Selected = false, Value = "Sale"});

                return View(new RegisterModel { RolesContainer = tempRoles });
    }

----View--------

@{ foreach (var item in Model.RolesContainer)
               {
                    @Html.DisplayFor(m => item.Text)
                    @Html.CheckBoxFor(m => item.Selected)
               }
            }

When I check them and submit, I get to the breakpoint in my Register action, but the RolesContainer is null at this point - can anyone tell me why this is?

Upvotes: 3

Views: 584

Answers (3)

Erik Philips
Erik Philips

Reputation: 54636

I copied and pasted your code (except the cshtml) into the following files and it works as expected.

HomeController.cs

using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<SelectListItem> tempRoles = new List<SelectListItem>();
            tempRoles.Add(new SelectListItem { Text = "Admin", 
                                               Selected = false, 
                                               Value = "Admin" });
            tempRoles.Add(new SelectListItem { Text = "Production", 
                                               Selected = false, 
                                               Value = "Production" });
            tempRoles.Add(new SelectListItem { Text = "Sale", 
                                               Selected = false, 
                                               Value = "Sale" });

            return View(new RegisterModel { RolesContainer = tempRoles });
        }

    }
}

RegisterModel

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MvcApplication1.Models
{
    public class RegisterModel
    {
        [Required]
        [Display(Name = "Brugernavn")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email adresse")]
        public string Email { get; set; }

        public List<SelectListItem> RolesContainer { get; set;}
    }
}

Home/Index.cshtml

@model MvcApplication1.Models.RegisterModel

@{ 
    foreach (var item in Model.RolesContainer)
    {
        @Html.DisplayFor(m => item.Text)
        @Html.CheckBoxFor(m => item.Selected)
    }
}

Most likely there is something wrong in your Register.cshtml file, of which we don't have to validate.

Upvotes: 2

fmgp
fmgp

Reputation: 1636

If I understand well (may be I'm totally wrong), the model you post to httppost register (RegisterModel) doesn't contains the RolesContainer you expect. I think, asp.net mvc is not able to match multiple checkboxes with a List<SelectListItem>, a ListBox should be better

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

Currently when you are assigning the value to RolesContainer it has not been initialised. You simply need to initialise it in the constructor of your class:

public class RegisterModel
{
    public RegisterModel() {
        RolesContainer = new List<SelectListItem>;
    }

    // rest of your code
}

Alternatively you could create a constructor which accepts the List<> as a parameter, but the above method will work for your current code structure.

Upvotes: 0

Related Questions