How to send multiple selected checkboxes checked value from nested loop using ajax?
In the above image, P means parent and C means child and 1 is attached to the computer, said computer is a child of electronics, also MySql is a child of computer programming .
I want to send multiple selected checkbox values ββusing ajax to my controller and filter the data based on the selected checked value.
This is my model:
public class sample
{
public int Id { get; set; }
public string parent { get; set; }
public virtual ICollection<childsample> childsamples { get; set; }
}
public class childsample
{
public int childid { get; set; }
public string child { get; set; }
}
My view (.cshhtml):
@foreach (var sample in Model.sample)
{
<label class="Parentlabel">
<input type="checkbox" name="parentHeader" class="ParentHeader Right5" />
@sample.parent
</label>
<div class="bgContainer">
@foreach (var child in @sample.childsamples)
{
<label class="childLabel">
<input class="ChildHeader Right5" type="checkbox" name="childHeader" value="@child.child" />@child.child
</label>
}
</div>
}
My controller:
Public ActionResult filterData(int [] checkedIds) // if id is passed as paramter from ajax
Can anyone tell me how can I send this number of checked boxes to my controller with ajax data and filter based on checked value?
+3
source to share
1 answer
Usage can be achieved with java script array
To get the parent id you have to check the parent checkbox also in the child checkbox
Html
<input type="checkbox" name="parentHeader" class="ParentHeader Right5" value="@sample.Id" /> @sample.parent
Ajax call
Call ajax function in both parent and child class
$(".ParentHeader, .ChildHeader").click(function () {
var parentValueToPush = new Array();
var childValueToPush = new Array();
// Parent checked check box value
$('.ParentHeader:checked').each(function () {
parentValueToPush.push($(this).val());
});
// Child checked check box value
$('.ChildHeader:checked').each(function () {
childValueToPush.push($(this).val());
});
var obj = {
ParentCheckedIds: parentValueToPush,
ChildCheckedIds: childValueToPush,
};
$.ajax({
url: '/Home/filterData',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: JSON.stringify(obj),
cache: false,
success: function () {
},
error: function (xhr, status, error) {
alert("Error");
}
});
});
controller
public void filterData(List<int> ParentCheckedIds, List<int> ChildCheckedIds)
{
// Code
}
+3
source to share