connectseekers.com

Friday, 11 July 2014

How to Bind CheckBoxlist By Model Data and Get Selected Value In Controller in asp.net MVC

7/11/2014 - By Pranav Singh 10

In this article I will show you how you can bind a checkboxlist in an mvc application using c#.net by using entity model and how you can retrieve the selected checkbox value in at controller. This article you an use in MVC3,MVC4 and MVC5.


So for this article first we will create a new mvc application. Now we will add model file in our project and add the below code.


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

namespace BindCheckBoxliatin_in_mvc.Models
{
    public class CountryModel
    {
        public List<Country> CountryList { get; set; }
    }
    public class Country
    {
        public int countryId { get; set; }
        public bool CheckedStatus { get; set; }
        public string CountryName { get; set; }
    }
}

Now we will add controller in our application and add the below code in it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BindCheckBoxliatin_in_mvc.Models;
using System.Text;

namespace BindCheckBoxliatin_in_mvc.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            CountryModel _objcountrymodel = new CountryModel();
            _objcountrymodel.CountryList = new List<Country>();
            _objcountrymodel.CountryList = BindCountry();
            return View(_objcountrymodel);
        }
        [HttpPost]
        public ActionResult Index(CountryModel _objcountrymodel)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECTED COUNTRY :- ").AppendLine();
            foreach (var item in _objcountrymodel.CountryList)
            {
                if (item.CheckedStatus == true)
                {
                    sb.Append(item.CountryName + ", ").AppendLine();
                }
            }
            ViewBag.Country = sb.ToString();
            return View(_objcountrymodel);
        }
        /// <summary>
        /// This method will provide data
        /// This mehod can be used for getting data from DB
        /// </summary>
        /// <returns></returns>
        public List<Country> BindCountry()
        {
            List<Country> _objcountry = new List<Country>();
            _objcountry.Add(new Country { countryId = 1, CountryName = "India" });
            _objcountry.Add(new Country { countryId = 2, CountryName = "Pakistan" });
            _objcountry.Add(new Country { countryId = 4, CountryName = "Sri Lanka" });
            _objcountry.Add(new Country { countryId = 5, CountryName = "Japan" });
            _objcountry.Add(new Country { countryId = 6, CountryName = "China" });
            return _objcountry;
        }

    }
}

In above code we have added httpget and httppost method both. In above code we have stored data viewbag to display at view end.

Now create view for the controller and add the below code.

@model BindCheckBoxliatin_in_mvc.Models.CountryModel
@{
    ViewBag.Title = "Index";
}
<h2>
    Bind CheckBoxList in MVC</h2>
@using (Html.BeginForm("Index", "Home"))
{
    <table width="100%">
        @for (int i = 0; i < Model.CountryList.Count; i++)
        {
            <tr>
                <td>
                    @Html.CheckBoxFor(m => Model.CountryList[i].CheckedStatus)
                    @Model.CountryList[i].CountryName
                    @Html.HiddenFor(m => Model.CountryList[i].countryId)
                    @Html.HiddenFor(m => Model.CountryList[i].CountryName)
                </td>
            </tr>
        }
        <tr>
            <td>
                <input type="submit" value="Submit" />
            </td>
        </tr>
            <tr>
            <td>
               @ViewBag.Country
            </td>
        </tr>
    </table>
}

 Now we will run the application and check the output. As you run the application we will get below screen.


Now we will select the value and click on submit button. You will get the data from view to controller as shown below.


Now we will press F5 to view the final output.



About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

10 comments:

  1. Now how do I bind this to a sql data table column?

    ReplyDelete
    Replies
    1. Hi
      You just need to follow the below step.

      1. Retrieve the data from database.

      2. now apply lop to add the DB value in the collection.
      EG:
      List _objcountry = new List();
      foreach(var item in countryTableDataFromDB)
      {
      _objcountry.Add(new Country { countryId =item.Id, CountryName = item.Name });
      }

      3. Now bind the as shown above

      Delete
    2. Ok, I can retrieve list from the database but I cannot post the data. That is the problem that I am having. How do I post the appended comma separated list to a table column?

      Delete
    3. If you are have value comma seprated on that case just assign it to a model property.

      if you are still facing problem then please attach the sample code of you application.

      Delete
  2. My view is the same as above I just added one line. I am trying to link it like this but it is not working. I do not want to use viewbag. I'm using EditorFor of which eventually will be turned into HiddenFor.

    @Html.EditorFor(model => model.Security_Access_To_1, Model.SecurityAccessList[i].Access_Name)

    ReplyDelete
  3. How do you implement this if you already have data in a table, having multiple views and showing the checkboxlist on the same view with other models?

    ReplyDelete
    Replies
    1. Hi Scrip,
      I am storing the detail in table and passing it to view. Now on view i am generating the checkbox on the bases of no of record on model. Just check the for loop.

      If this is not the answer of you question please explain me ur exact problem which you are facing.

      Delete
  4. Can you send the code? It's not work for me. model column id and selectt return null
    I don't know what I forget.

    ReplyDelete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com
Email Id : contact@aspdotnet-pools.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Top jQuery Plugins

Global Classified : Connectseekers.com
© 2014
back to top