Login


1
  Oracle
1
Training Program on Practical Oracle
06 Mar 2015| mamunbssit

In this post, I will explain two methods to implement CheckBoxList in ASP.NET MVC. I work in MVC 4 with .NET Framework 4.5.1 and Visual Studio 2013.This post comes after I surfed a little bit of How to implement CheckBoxList in my new project.

Using the Code

Here, we will create ASP.NET MVC project to start with.

First: Write the Model

In the Models Folder, add the following classes:

// public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public ICollection Groups { get; set; }
    }
    public class Group
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection Users { get; set; }
    }
//

Our model will represent the user - group Relationship, it is clear it is many-to-many Relation, so we will manage user groups via checkListBox.

Note: This is not a complete example for managing Groups of users. It is just for clearing CheckBoxList.

Second: Write the ViewModel

Make a new folder in the solution. Name it ViewModel and add the class.

// public class UserViewModel
    {
        public User User { get; set; }
        public List AllGroups { get; set; }
        public List UserGroups { get; set; }
        public int[] SelectedGroups { get; set; }
    }
//

Third: Change Controller

Add the following method to HomeController.cs:

private UserViewModel InitilizeData()
        {
            UserViewModel userVM = new UserViewModel();
            userVM.User = new Models.User
            {
                ID = 1,
                Name = "Ahmed Omer",
                Password = "123123",
                Email = "a@b.c"

            };
            userVM.User.ID = 1;
            userVM.User.Name = "Ahmed Omer";
            userVM.User.Password = "123123";
            userVM.User.Email = "a@b.c";
            userVM.AllGroups = new List() {
                new Group {ID=1,Name="Group 1" },
                new Group {ID=2,Name="Group 2" },
                new Group {ID=3,Name="Group 3" },
                new Group {ID=4,Name="Group 4" },
                new Group {ID=5,Name="Group 5" }
            };

            userVM.UserGroups = new List()
            {
                userVM.AllGroups[4],
                userVM.AllGroups[1],
                userVM.AllGroups[2],
            };
            userVM.SelectedGroups = userVM.UserGroups.Select(x => x.ID).ToArray();
            return userVM;
        }

Index action should look like this:

// public ActionResult Index()
        {
            return View(InitilizeData());
        }
        [HttpPost]
        public ActionResult Index(UserViewModel model)
        {
            UserViewModel user = InitilizeData();
            user.SelectedGroups = model.SelectedGroups;
            //add code to manipulate user groups             //foreach (var item in user.SelectedGroups)             //{             //             //}             return View(user);
        }
//

Forth: Direct to View

In the index view, replace all code with the following:

@model CheckBoxList.ViewModels.UserViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>UserViewModel</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.ID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.ID)
            @Html.ValidationMessageFor(model => model.User.ID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.Name)
            @Html.ValidationMessageFor(model => model.User.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.Password)
            @Html.ValidationMessageFor(model => model.User.Password)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.User.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User.Email)
            @Html.ValidationMessageFor(model => model.User.Email)
        </div>
        <ul>
            @foreach (var g in Model.AllGroups)
            {
                <li>
                    <input type="checkbox" 
                    name="SelectedGroups" value="@g.ID" id="@g.ID"
                           @{if (Model.SelectedGroups.Contains(g.ID)) 
                           { > checked='checked' </text>  } } />
                    <label for="@g.ID">@g.Name</label>
                </li>
            }
        </ul>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

The main code we are interested in is:

<ul>
            @foreach (var g in Model.AllGroups)
            {
                <li>
                    <input type="checkbox" 
                    name="SelectedGroups" 
                    value="@g.ID" id="@g.ID"
                           @{if (Model.SelectedGroups.Contains(g.ID)) 
                           { > checked='checked' </text>  } } />
                    <label for="@g.ID">@g.Name</label>
                </li>
            }
        </ul>

The ouput should look like this:

Your Comments



  Info
Views 100
First Posted :3/6/2015