This project is read-only.

CheckBoxList Model

This model is used when you would like a list of check boxes posted to your form into a string[]. This model does not use the default Check box Helper because it allows strings as values.

The class is very simple
public class CheckBoxList
{
    public object[] SelectedOptions { get; set; }
    public IEnumerable<SelectListItem> Options { get; set; }
}

The Roles Use Case
public class UserViewModel
{
    public string UserName { get; set; }
    public CheckBoxList Roles { get; set; }
}

[HttpGet]
public ActionResult EditUser( int id )
{
    var user = UserRepository.FindById( id );
    var roles = RoleRepository.FindAll();

    var roleCheckBoxes = new CheckBoxList()
                                {
                                    SelectedOptions = user.Roles.Select( x => x.RoleId ).ToArray(),
                                    Options = roles.Select( x => new SelectListItem {Text = x.RoleName, Value = x.RoleId} )
                                };
    var vm = new UserViewModel
                    {
                        UserName = user.UserName,
                        Roles = roleCheckBoxes
                    };

    return View( vm );
}

[HttpPost]
public ActionResult EditUser( int id, UserViewModel model )
{
    if ( !ModelState.IsValid )
        return RedirectToAction( "EditUser", new {id} );

    model.SelectedOptions = model.SelectedOptions ?? new object[0];

    var user = UserRepository.FindById( id );

    user.UserName = model.UserName;

    var userRoles = user.Roles.ToList();
    userRoles.RemoveAll( x => !model.Roles.SelectedOptions.Contains( x.RoleId ) );
    var currentRoleIds = userRoles.Select( x => x.RoleId );

    foreach( var role in model.Roles.SelectedOptions.Where( x => !currentRoleIds.Contains( x ) ) )
    {
        userRoles.Add( RoleRepository.FindById( role ) );
    }

    user.Roles = userRoles;
    UserRepository.Upadate( user );

    return RedirectToAction( "EditUser", new {id} );
}

Last edited Feb 21, 2011 at 5:38 AM by brk6004, version 5

Comments

No comments yet.