Galago08
Galago08

Reputation: 21

How to send Array from Select List to ajax

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

Upvotes: 1

Views: 1041

Answers (1)

Rena
Rena

Reputation: 36715

1.You could get selected array like below:

$('#assignedCategory').val();

2.Upon you select an option in selectlist, the onchange event will be triggered. That is to say if you select multiple options, it will trigger GetSubCat function for multiple times and post to backend for multiple times. If you do not care with this. Just change ajax post data to: $('#assignedCategory').val();.

3.You use selectpicker in your code, it seems you use Bootstrap-select plugin in your project. Bootstrap-select exposes a few events for hooking into select functionality. I think you could use hidden.bs.select event to post your selected array list to backend. This event is fired when the dropdown has finished being hidden from the user. That is to say it will trigger ajax upon the select menu closed.

Here is a working sample:

<div class="col-lg-3 col-md-3 col-sm-3" id="category">   //add id here...
    <select id="assignedCategory" class="form-control selectpicker" title="Category" value="@ViewBag.AssignedCategory" multiple >
        <option value="1">aa</option>
        <option value="2">bb</option>
        <option value="3">cc</option>
    </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>
@section Scripts
{
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.min.css">    
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js"></script>
    <script>
        $('#category').on('hide.bs.select', function (e) {
             $.ajax({
                  url: '@Url.Action("GetSubCat")',
                  type: 'post',
                  dataType: 'json',
                  data: {
                      CatId: $('#assignedCategory').val()
                  },
                  success: (data) => {
                   $.each(data, (i, e) => {
                    var elem = '<option value="' + e.value + '">' + e.text + '</option>'
                    $('#assignedSubCategory').append(elem);
                    $('#assignedSubCategory').selectpicker('refresh');
                   });
                  }
                 });
        });       
    </script>
}

Upvotes: 1

Related Questions