Click here to Skip to main content
11,570,906 members (59,794 online)
Click here to Skip to main content

Tagged as

ASP.Net MVC- How to implement CheckBoxList?

, 4 May 2014 CPOL 5.9K 6
Rate this:
Please Sign up or sign in to vote.
CodeProject In the last blog post on ASP.Net MVC, we have discussed about setting initial selected value in a RadioButtonList. You can read that article here. In this article we will go over implementing CheckBoxList  in ASP.Net MVC. Let’s try to understand this with an example. We will be usi

In the last blog post on ASP.Net MVC, we have discussed about setting initial selected value in a RadioButtonList. You can read that article here. In this article we will go over implementing CheckBoxList  in ASP.Net MVC.

Let’s try to understand this with an example. We will be using tblCity table in this example.

MVC1

The SQL scripts for creating tblCity table and inserting data into it are following:

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’, 1)
Insert into tblCity values (‘Sydney’, 1)
Insert into tblCity values (‘Mumbai’, 0)
Insert into tblCity values (‘Cambridge’, 0)

Our ultimate intention is to generate a screen like below.

MVC2

The requirements are following:

When a user selects one or more cities and click on Submit button, the selected cities should be displayed in a comma separated manner. When the user doesn’t select  any of the cities and still clicks on Submit button, a message of You have not selected any City should be appeared.

Let’s try to achieve this. First of all, add an ADO.Net data model to retrieve data from the database. For this, follow below steps.

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.

MVC3

4. On Entity Data Model Wizard, select Generate from database and click Next.

MVC4

5. Check Save entity connection settings in Web.Config as checkbox.

6. Type SampleDBContext as the connection string name and click Next.

MVC5

7. On the next screen, expand Tables and select tblCity table.

MVC6

8. Type Models in Model Namespace textbox and click Finish.

As soon as we click on Finish button, a Model like below will be created.

MVC7

 A connection string will automatically be added to the Web.config file as well.

MVC8

Then right click on the Views folder and add a Home folder. Again right click on the Home folder and add EditorTemplates folder.

Then right click on EditorTemplates folder => Add  =View. In the Add View dialog box, set

View Name = tblCity
View Engine = Razor

Model class = tblCity(MVCDemo.Models) and click Add.

MVC9

Copy and paste the following code in tblCity.cshtml.

@model MVCDemo.Models.tblCity

@{
    ViewBag.Title = “City”;
}

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

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

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

MVC10

Then right click on the Controllers folder and add a HomeController. Don’t forget to include following 2 namespaces in HomeController.

using MVCDemo.Models;
using System.Text;

Copy and paste the following code to the HomeController.

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

[HttpPost]
public string Index(IEnumerable<tblCity> 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 (tblCity city in cities)
        {
            if (city.IsSelected)
            {
                sb.Append(city.Name + “, “);
            }
        }
        sb.Remove(sb.ToString().LastIndexOf(“,”), 1);
        return sb.ToString();
    }
}

MVC11
Then right click on the Index action method in HomeController and select Add View from the context menu.

Set View Name = Index

View Engine = Razor and click Add.

Copy and paste the following code in Index.cshtml.

@model IEnumerable<MVCDemo.Models.tblCity>
@{
    ViewBag.Title = “Index”;
}
<div style=”font-family:Arial”>
<h2>Index</h2>

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

MVC12

Now run the application and we will get a screen like below.

MVC13

When we select some cities, say New York and Sydney and click on Submit button, a message like below will be appeared.

You selected – New York, Sydney

MVC14

Without selecting any cities and clicking on Submit button, a message like below will be appeared as expected.

You have not selected any City

MVC15

MVC16

Reference: Arun Ramachandran (http://BestTEchnologyBlog.Com)


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Arun Ramachandran India
Software Developer
India India
Arun Ramachandran is a Software Engineer having hands on experience in different Microsoft Technologies who is presently working in Experion Technologies, India. He has written over 95 articles on the subject on his blog at http://BestTEchnologyBlog.com. Along with 3 years of hands on experience he holds a Master of Computer Applications degree from Cochin University of Science & Technology (CUSAT).

You may also be interested in...

Comments and Discussions

 
Questionnice article Pin
Member 109374483-Aug-14 22:45
memberMember 109374483-Aug-14 22:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 5 May 2014
Article Copyright 2014 by Arun Ramachandran India
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid