I'm new to Ajax and I can't find any way to pass my data Properly, my Sub-Category is dependent on categories output, my problem now is that when I select 2 or more item in category, the output of Sub-Category don't pile up on each other.
I know I have to put my category on array but I don't know how it will work if the data come on select list.
My Filter
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedCategory" class="form-control selectpicker" title="Category" value="@ViewBag.AssignedCategory" asp-items="@ApplicationCategory" multiple asp-for="@category" onchange="GetSubCat();">
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedSubCategory" class="form-control selectpicker" title="Sub-Catergory" multiple>
</select>
</div>
Ajax
function GetSubCat() {
$('#assignedSubCategory').html('');
$.ajax({
url: '@Url.Action("GetSubCat")',
type: 'post',
dataType: 'json',
data: {
CatId: $('#assignedCategory option:selected').val() <!--This Part Right Here, I don't know how to make this an Array.-->
},
success: (data) => {
$.each(data, (i, e) => {
var elem = '<option value="' + e.value + '">' + e.text + '</option>'
$('#assignedSubCategory').append(elem);
$('#assignedSubCategory').selectpicker('refresh');
});
}
});
}
Controller
[HttpPost]
[AllowAnonymous]
public JsonResult GetSubCat(int?[] CatId)
{
var getCat = db.Subcategories.FromSqlRaw($@"
select sc.* from CRM_Subcategories sc
left join CRM_Categories c on sc.CategoryId = c.Id
where c.Id IN ({CatId})").Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Value
}).ToList();
return Json(getCat);
}