Checkbox list with list & model binding in MVC 5


In this post we will learn How to implement Checkbox list in mvc 5 with model

Model:

First create Model as follows

Player Model
public class Player
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsSelected { get; set; }
    }

Now let’s create action method in controller class

Action Method for checkboxlist
public ActionResult cbxList(IEnumerable<Player> model)
        {
            IEnumerable<Player> palyers = new List<Player>() {
                new Player(){Id = 1, Name = "Venki"},
                new Player(){Id = 2, Name = "Karthikeya"},
                new Player(){Id = 3, Name = "Ravi"},
                new Player(){Id = 4, Name = "Prasad"},
                new Player(){Id = 5, Name = "Hari"}
            };
            if (model == null)
                model = palyers;
            return View(model);
        }

Now lets create Editor Template for the player model as follows:

first create a folder with name “EditorTemplates” under Views folder for your controller

Write the following code in that Editor Template

Editor Template
@model MVCControls.Models.Player

@{
    ViewBag.Title = "Player";
}

@Html.HiddenFor(p => p.Id)
@Html.HiddenFor(p => p.Name)
@Html.CheckBoxFor(p=>p.IsSelected)
@Html.DisplayFor(p => p.Name)

Now create a view for the current action method

View for the actionmethod
@model IEnumerable<MVCControls.Models.Player>
@{
    ViewBag.Title = "cbxList";
}

<h2>Checkbox lsit in MVC 5</h2>

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <br />
    <input type="submit" value="Submit" />
    if (Model.Count(n => n.IsSelected) > 0)
    {
        <br />
        @Html.Label("Selected Players are:")<br />
        foreach (var item in Model.Where(n => n.IsSelected))
        {
            @Html.Label(item.Name)<br />
        }
    }
}

Now Rebuild the application and Run.

image

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s