Home > DeveloperSection > Beginner > Checkbox control in MVC

Checkbox control in MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
15 Comment(s)
 28275  View(s)
Rate this:

Checkbox control in MVC

In this article I am going to explain how to create checkbox control and how to get the selected checkboxes value in MVC.

Here in the Model class I have created a property named Hobbies that is of type List<string>, that return some natural hobbies such as Cricket, Football, Hockey stored in a property as I have mentioned below;

using System.Collections.Generic;

using System.Web;

namespace CheckBoxMVC.Models

{

    public class ModelClass

    {

        public List<string> Hobbies

        {

            get

            {

                List<string> hobby = new List<string>();

                hobby.Add("Cricket");

                hobby.Add("Football");

                hobby.Add("Hockey");

                return hobby;

            }

        }

    }

}


After completing the section of Model, here in the Controller class I have created two Action methods. First Index method that return a View along with the object of ModelClass and in the second action method i.e. Show which check the state of checkbox and stores selected checkbox value in a variable.

using System.Collections.Generic;

using System.Web;

using System.Web.Mvc;

using CheckBoxMVC.Models;

 

namespace CheckBoxMVC.Controllers

{

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View(new ModelClass());

        }

 

        [HttpPost]

        public string Show(FormCollection postedForm, ModelClass model)

        {

            string val = "";

            foreach (var category in model.Hobbies)

            {

                if (postedForm[category].ToString().Contains("true"))

                {

                    val = val + " " + category;

                }

            }

            return "Selcted hobbies are: <b>" + val + "</b>";

        }

    }

}


After performing the above tasks, you have to create the checkbox in a View which displays the hobby that is return by a property of Model. Also create a submit button on click of which selected hobbies are displayed or we can say selected checkboxes values are displayed.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<CheckBoxMVC.Models.ModelClass>" %>

 

<!DOCTYPE html>

<html>

<head runat="server">

    <title>Index</title>

</head>

<body>

    <% using (Html.BeginForm("Show", "Home", FormMethod.Post))

       { %>

    <div>

        <b>Select Hobbies : </b>

        <% foreach (string hobby in Model.Hobbies)

           { %>

        <%: Html.CheckBox(hobby)%><%: hobby%>

        <%} %>

        <br /><br />

        <input type="submit" value="Submit" />

    </div>

    <%} %>

</body>

</html>


After performing the above tasks, we can see the output of our application in a browser with the multiple checkboxes.

Checkbox control in MVC

When a submit button is pressed selected hobbies are displayed.

Checkbox control in MVC

By using above process you can simply learn that how to create checkbox and get a selected checkbox value in MVC.

 


postedForm[category] is null

By Kevin Scanton on   4 years ago

I tried your code and got null value on postedForm[category]

Not sure why


Checkbox control in MVC

By Haider M Rizvi on   4 years ago

Kevin,

I have checked the above code and tried to regenerate the error specified by you, but was unable to do so, as it is working fine.

I think you might be doing something wrong.

Could you please post your Controller and View code here, so that we can identify the real issue.

Thanks.


Checkbox control in MVC

By Kevin Scanton on   4 years ago

I ported the code to MVC Razor, prob I'm missing something. So here's the code:

Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MvcTestCheckbox.Models;


namespace MvcTestCheckbox.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            

            return View(new ModelClass());
        }

        [HttpPost]

        public string Show(FormCollection postedForm, ModelClass model)
        {

            string val = "";

            foreach (var category in model.Hobbies)
            {
                if (postedForm[category] == null)
                    continue;
                if (postedForm[category].ToString().Contains("true"))
                {
                    val = val + " " + category;
                }
            }
            return "Selected hobbies are: <b>" + val + "</b>";

        }

    }
}

View:

@model MvcTestCheckbox.Models.ModelClass
@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("Show","Home",FormMethod.Post))
{
    <div>
   Select hobbies:

   @foreach (string hobby in Model.Hobbies)
    {
        @Html.CheckBox("ckbox");
        @hobby
       
    } 
    <br /><br />
    <input type="submit" value="Submit" />
    </div>
}

What am I missing?

Thanks.


Checkbox control in MVC

By Awadhendra Tiwari on   4 years ago
Hi Kevin,
I had checked your code and I got problem in your views. When you are creating check box in view, you are passing ID as "ckbox" which is incorrect according to logic of your controller. Please update your view code by code given below. Its work as I had check it.

Modified view code

@model MvcApplication5.Models.ModelClass
@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("Show", "Home", FormMethod.Post))
{
    <div>
        <b>Select Hobbies : </b>
        @foreach (string hobby in Model.Hobbies)
        {
            @Html.CheckBox(hobby) @:@hobby
                }
        <br />
        <input type="submit" value="Submit" />
    </div>
}

I had marked it as bold which cause the problem in older code which you had provide.
Note: Please do not use semicolon
Thanks.

Checkbox control in MVC

By Kevin Scanton on   4 years ago

Yes it worked now. Thank you!


Checkbox control in MVC

By Kevin Scanton on   4 years ago

If I don't use Html.BeginForm then how do I go about checking if a checkbox is checked in the Controller code since we don't have FormCollection anymore. What I mean is putting href of Url.Action next to the CheckBox in View but not sure how those checkboxes being captured in Controller.

Thanks.


Checkbox control in MVC

By Rohit Kesharwani on   4 years ago
Hi,

If you don't have FormCollection, you can do something like below:

Model code:

     public class Model
    {
        public List<SampleData> Hobbies
        {
            get
            {
                List<SampleData> hobby = new List<SampleData>();
                hobby.Add(new SampleData()
                {
                    Id = "Cricket",
                    Name = "Cricket"
                });
                hobby.Add(new SampleData()
                {
                    Id = "Football",
                    Name = "Football"
                });
                hobby.Add(new SampleData()
                {
                    Id = "Hockey",
                    Name = "Hockey"
                });
                return hobby;
            }
        }
    }
    public class SampleData
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

Create the View as give below:

         <% using (Html.BeginForm("ShowData", "Home"))
           {  %>
        <% foreach (var o in Model.Hobbies)
           { %>
        <input type="checkbox" name="selectedObjects" value="<%=o.Name%>">
        <%= o.Name %>
        <%}%>
        <input type="submit" value="Submit" />
        <%}%>

Then in the Controlller, define the following methods:

        public ActionResult Index()
        {
            return View(new Model());
        }
        public string ShowData(string[] selectedObjects)
        {
            string val = "";
            if (selectedObjects != null)
            {
                foreach (string guid in selectedObjects)
                {
                    val = val + " " + guid.ToString();
                }
            }
            return "Selcted hobbies are: <b>" + val + "</b>";
        }

Try it. I think it will help you.

Checkbox control in MVC

By Kevin Scanton on   4 years ago

Thanks Rohit. In my case, I really wish to avoid using Html.BeginForm in View since it screws up other controls in my page. Something like the following pattern that I currently have for those controls.

@model TestCheckbox2.Models.ModelClass
@{
    ViewBag.Title = "Home Page";
}

@foreach (var o in Model.Hobbies)
{
    <input type="checkbox" name="selectedObjects" value="@o.Name"/> @o.Name
}
<br />
<br />
<a href="@Url.Action("ShowData", "Home", new { SelectedObjects = ???? })"><input type="submit" name="button" value="Submit" /></a>

What parameter that I should pass in View and how to handle selected items in Controller?

Thanks, kev

 

 


Checkbox control in MVC

By Kevin Scanton on   4 years ago
I should also mention that currently in my View page I have thumbnails and a checkbox for each. My goal is to: 1)process selected thumbnails 2)select thumbnails in current page 3) unselect thumbnails in page 4)select all 5)unselect all
Thanks
Kev
 

Checkbox control in MVC

By Rohit Kesharwani on   4 years ago
Hi Kevin,

If you don't want to use Html.BeginForm, then you have to use form tag in order to process your action, as given below:

<form action="\Home\ShowData">
    <div>
        <% foreach (var o in Model.Hobbies)
           { %>
        <input type="checkbox" name="selectedObjects" value="<%=o.Name%>">
        <%= o.Name %>
        <%}%>
        <input type="submit" value="Submit" />
    </div>
</form>

Without using form, you can not process your action.

Thanks.

Checkbox control in MVC

By Kevin Scanton on   4 years ago
Thanks Rohit.
What about paging, how would you pass the page number to Controller so I could remember those checkboxes and browse page back and forth? 
Thanks.

Checkbox control in MVC

By Awadhendra Tiwari on   4 years ago
Kevin,
You can post your questions on our Forum section..
http://www.mindstick.com/mindForum/Topic.aspx

Checkbox control in MVC

By Awadhendra Tiwari on   4 years ago
Kevin,
Please check this forum post..
http://www.mindstick.com/Forum/379/Checkbox%20control%20in%20MVC
Thanks,

Checkbox control in MVC

By Rohit Kesharwani on   4 years ago
hi kevin,

you can view this blog to do paging and passing the page number:

http://mindstick.com/Blog/279/Paging%20in%20ASP%20NET%20MVC

Thanks.

Checked box onload. how?

By Reynan Capco on   one year ago
hello. How can i load the data as checked? for example i save it in database. and try to load it. 
how can i add checked in this code?
hobby.Add("Cricket");

Don't want to miss updates? Please click the below button!

Follow MindStick