Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 38 - CheckBoxList in asp.net mvc

Suggested Videos 
Part 35 - How to set an item selected when dropdownlist is loaded
Part 36 - Difference between Html.TextBox and Html.TextBoxFor
Part 37 - Generating a radiobuttonlist control in mvc using HTML helpers

In this video we will discuss implementing a checkbox list in asp.net mvc. We will be using table "tblCity" for this demo.




We should be generating a checkbox for each city from the table tblCity.
implementing checkboxlist in asp.net mvc



Sql script to create table tblCity
CREATE TABLE tblCity
(
ID INT IDENTITY PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
IsSelected BIT NOT NULL
)

Insert into tblCity values ('London', 0)
Insert into tblCity values ('New York', 0)
Insert into tblCity values ('Sydney', 1)
Insert into tblCity values ('Mumbai', 0)
Insert into tblCity values ('Cambridge', 0)

Let's add ADO.NET data model, to retrieve data from database
1. Right click on the "Models" folder > Add  > Add New Item
2. From "Add New Item" dialog box, select "ADO.NET Entity Data Model"
3. Set Name=SampleDataModel.edmx and click "Add"
4. On "Entity Data Model" wizard, select "Generate from database" and click "Next"
5. Check "Save entity connection settings in Web.Config as:" checkbox
6. Type "SampleDBContext" as the connection string name and click "Next"
7. On "Choose Your Database Objects" screen, expand "Tables" and select "tblCity" table
8. Type "Models" in "Model Namespace" textbox and click "Finish"
9. Change the entity name from "tblCity" to "City"


Right click on the "Controllers" folder, and add a "HomeController". Include the following 2 namespaces in "HomeController"
using MVCDemo.Models;
using System.Text;

Copy and paste the following code.
[HttpGet]
public ActionResult Index()
{
    SampleDBContext db = new SampleDBContext();
    return View(db.Cities);
}

[HttpPost]
public string Index(IEnumerable<City> cities)
{
    if (cities.Count(x => x.IsSelected) == 0)
    {
        return "You have not selected any City";
    }
    else
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("You selected - ");
        foreach (City city in cities)
        {
            if (city.IsSelected)
            {
                sb.Append(city.Name + ", ");
            }
        }
        sb.Remove(sb.ToString().LastIndexOf(","), 1);
        return sb.ToString();
    }
}

Right click on the "Views" folder, and a "Home" folder. Right click on the "Home" folder and "EditorTemplates" folder. 

Right click on "EditorTemplates" folder > Add > View. In the "Add View" dialog box, set
View Name = City
View Engine = Razor
and click "Add".

Copy and paste the following code in "City.cshtml"
@model MVCDemo.Models.City

@{
    ViewBag.Title = "City";
}

@Html.HiddenFor(x => x.ID)
@Html.HiddenFor(x => x.Name)

@Html.CheckBoxFor(x => x.IsSelected)

@Html.DisplayFor(x => x.Name)

Please Note: Put the templates in "Shared" folder, if you want the "Templates", to be available for all the views.

Right click on the "Index" action method in "HomeController", and select "Add View" from the contex menu. Set 
View Name = Index
View Engine = Razor and click "Add"

Copy and paste the following code in "Index.cshtml"
@model IEnumerable<MVCDemo.Models.City>
@{
    ViewBag.Title = "Index";
}
<div style="font-family:Arial">
<h2>Index</h2>

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <br />
    <input type="submit" value="Submit" />
}
</div>

13 comments:

  1. How to get the selected data on another page .

    ReplyDelete
    Replies
    1. various way to send selected data to another page, 1- Using FormCollection. 2- Use data model object.

      Delete
  2. How to use this helper in Create page?and how to display what i select item?

    ReplyDelete
  3. how to pass collection of model class from view to controller without using editor templatpe?

    ReplyDelete
    Replies
    1. You can loop with for in your view. Use IList instead of IEnumerable

      Delete
  4. Getting an error like con not convert implicitly the type bool? to bool.

    ReplyDelete
  5. type isselected.value for convert implicity typeto bool

    ReplyDelete
  6. how to enter the checkboxlist value to database using entityframework

    ReplyDelete
  7. i am very confused
    (1) what happens when we check the checkbox?
    (2) how isSelected is updated ?
    (3) when the form is posted dowe receive all checkboxes or only the selected ones?
    (4)In foreach loop we are checking
    if (city.isSelected)
    {
    sb.Append(city.Name + ", ");
    }
    how isSeleced is updated??????

    ReplyDelete
  8. From where the Cities Property comes in this code and all other parts :-

    [HttpGet]
    public ActionResult Index()
    {
    SampleDBContext db = new SampleDBContext();
    return View(db.Cities);
    }

    ReplyDelete
  9. i get out 1234 with submit button . after all the code ?
    do not get checkbox , is there is any solution for that

    ReplyDelete
  10. hii venkat i wanna functionality like , if i submitted the from using Submit button okay , but if some one does back the page using browser then i wanna first time displayed checkboxes.

    ReplyDelete
  11. Hi Venkat,

    Could you please let me know how to post the data back to data base from check box, I know you showed us to to display what checked boxes user check on UI, what if we want to save that data how do we do that, I would really appreciate if you could have something information for me.

    Thanks
    Ali

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.