Home > DeveloperSection > Forums > Pass checked checkboxes to controller through ajax
Ashish Pandey

Total Post:128

Points:898
Posted on    March-26-2014 3:46 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 787  View(s)
Rate this:

I am developing a project on ASP.net MVC.

I have a html form with some checkboxes say A,B,C,D & E and I am posting the form through ajax to one of the controllers.

I would like to distinctly identify if each check boxes are checked from the controller and perform some action based on the selected checkbox value.

I would like to know the best practise to acheive this.



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-26-2014 4:26 AM

Hi Ashish,

You can do it in many ways. Here i'm giving a example-

Using a model object

Lets assume, you have a model "CheckBoxValues" in server side with the fields

public class CheckBoxValues

{

    public Boolean A { get; set; }

    public Boolean B { get; set; }

}

On your html page, use the code to get values from the checkboxes on a button click handler-

var values= {};

var StateOfCheckBoxA = $('#CheckBoxA').is(':checked');

values.A= StateOfCheckBoxA  ;

var StateOfCheckBoxB = $('#CheckBoxB').is(':checked');

values.B= StateOfCheckBoxB;

var SubmitURL = YourController/ActionMethod/

            $.ajax({

                type: "POST",

                url: SubmitURL,

                data: values,

                dataType: 'json',

                beforeSend: function () {

                },

                success: function (result) {

                },

                error: function (request, status, error) {

                },

                complete: function () {

                }

            });

Now your actionmethod

 public JsonResult Create(CheckBoxValues values)

 {

       Boolean checkboxA=values.A;

       Boolean checkboxB=values.B;

 }

Hope this will help you.


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

Follow MindStick