This project is read-only.

How am I doing CheckBoxListFor wrong?

Apr 20, 2011 at 10:29 PM

Hi everyone,

Put this here because I don't think it's an issue. I just think I'm uninformed.

I'm posting the following data to have a user add another user and assign them rolls.

The model is as shown.

    public class RegisterModel
    {
        private List<string> _roles = new List<string>();

        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

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

        [Display(Name = "Roles")]
        public List<string> Roles
        {
            get { return _roles; }
            set { _roles = value; }
        }

        public static List<string> AllRoles
        {
            get { return new RolesService().GetAllRoles().ToList(); }
        }
    }

I'm using the CheckBoxListFor to have the user select roles for the user.

The View looks like this.

            <div class="editor-label">
                <%: Html.LabelFor(model => model.Roles) %>
            </div>
            <div class="editor-field">
                <%: Html.CheckBoxListFor(model => (model.Roles), new ChoiceList<string, string, string>(RegisterModel.AllRoles, (r => r), (r => r)))%>
            </div>

When the controller get's the model back after the post, Roles is null! Any hints, anyone?

Thanks,
Andrew 

Coordinator
Apr 21, 2011 at 7:45 PM

I don't see any evident error. does the list displays correctly before the post?

The only anomaly is that you use just the name of the role, normally one uses a role code and a role name and passes something like r => r.Name and r => r.Code. However this shouldn't be an issue if you

are sure that the role names have no duplicates

On the other side the problem might be the controller. Can you please show the code of your controllers (expecially the Action method that receives the post)?

Apr 21, 2011 at 8:03 PM

The code is attached below. I'm using the role name alone because I'm using the Asp.Net SqlRoleProvider and the "GetRoles()" of that provider, which only supplies strings. There are no duplicates, they are not allowed in SqlRoleProvider.

The code is attached below. Just so you know, on the post, model.Roles is null upon entry to the the post controller, but the UserName and Email exist.

Thanks!

        public ActionResult AddNewUser()
        {
            return View(new RegisterModel());
        }

        [HttpPost]
        public ActionResult AddNewUser(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                if (String.IsNullOrWhiteSpace(model.Email))
                    model.Email = "none@none.com";

                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, "?", model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    RolesService.AddUserToRoles(model.UserName, model.Roles.ToArray());
                    ViewBag.Messages.Add("User successfully created");
                    return AddNewUser();
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                    ViewBag.Messages.Add(AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }
Coordinator
Apr 21, 2011 at 10:21 PM

Have you registred the extensions of the MvcControlsToolkit in your global.asax as shown below?

protected void Application_Start()
        {
            MVCControlsToolkit.Core.Extensions.Register();//this is the line of code to add
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
The only explanation that comes in my mind is that you forgot this,...I have tried an example similar to yours on my computer and it works.

Apr 21, 2011 at 10:43 PM

Silly Frank.

Only people who read the manual would know that. Don't you know no one reads the manual :)

Thanks a ton. Of course that was it.

Andrew