Anup Anup - 1 month ago 12
Ajax Question

MVC - Sending List of Values to AJAX call

I have a Modal that opens & gives User options to check some checkboxes. When the User checks checkboxes of his choice. I want to send all the values of checkboxes & call AJAX method.

I want to send values of selected checkboxes to the Controller method.

Here is my Code :-

// These are dynamic checkboxes - This is just an e.g
<input type="checkbox" name="name" value="Code">
<input type="checkbox" name="name" value="Code1">
<input type="checkbox" name="name" value="Code2">
<input type="checkbox" name="name" value="Code3">

// onClick event of Button
jq.get('/Controller/getData', function (data) {
jq('#placeHolder').html(data);
});

// Controller
[HttpGet]
public ActionResult getData()
{
return PartialView("_pagepartial");
}

Answer

To get the values of the checked checked boxes and add to an array

var array = [];
$('input:checked').each(function() {
  array.push($(this).val());
}

And to pass to you controller

$.ajax({
  type: "GET",
  url: '@Url.Action("getData", "Controller")',
  dataType: "html",
  traditional: true,
  data: { values: array},
  success : function (data) {
    $('#placeHolder').html(data);
  }
});

assuming you controller method is

public ActionResult getData(string[] values)
{
  // return some partial view based on values
}