Wednesday, 18 June 2014

Pass values of checkBox to controller action in asp.net mvc4




 

Description:-

 

In this example I explain that how to Pass values of checkBox to controller action method in asp.net mvc4 or Get checkbox values in controller mvc 4.

 

In previous example we already explain that How to Bind checkboxlist in mvc but now how to pass checked checkbox value to controller action method. To do this first you create the table tblcity with three column like id, name, isselected and insert data in this table.


to sorting data in gridview with up and down arrow sorting data in gridview in asp.net


change the background of gridview row when mouse is hover changebackground color of gridview in asp.net

 

Here in this example we implement that checkboxes with city and When a user selects one or more cities(checkbox) and click on Submit button, then  selected cities(checkbox) should be displayed in a webpage.

 

Checkbox Binding 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)


Now create a controller and put this code in this file. To do this first you have to include two namespace like

using MVCDemo.Models;
using System.Text;


HomeController code:-

[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();
    }
}

Now add razor view page with name like Index.cshtml and put this code in this file

@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> 


This entry was posted in :

0 comments:

Post a Comment