Pinch
Pinch

Reputation: 4207

How to Jquery Ajax Post a Multiple Select

I need to be able to be able to receive an array of CategoryIDs:

But I am getting null?!? Any ideas?

[HttpPost]
public ActionResult AddChargeCategories(int[] CategoryIDs, int ChargeID)
{
    foreach (var CategoryID in CategoryIDs)
    {
        db.ChargeCategories.Add(new ChargeCategory() { CategoryID = Convert.ToInt32(CategoryID), ChargeID = ChargeID });

    }
    db.SaveChanges();
    return RedirectToAction("Edit", new { id = ChargeID });
}



<select multiple="multiple"  id="CategoriesBefore" size="@DDCategories.Count" style="width:180px;">
@foreach (var Category in DDCategories)
{
    <option value="@Category.CategoryID">@Category.Name</option>    
}
</select>

<button onclick="return AddButton()">Add</button>

<script>

function AddButton() {

alert($('#CategoriesBefore').val());

$.ajax({

    url: '@Url.Action("AddChargeCategories")',
    type: "POST",
    data: { ChargeID: $("#ChargeID").val(), CategoryIDs: $('#CategoriesBefore').val() }
});


return false;

}

</script>

Upvotes: 1

Views: 2885

Answers (1)

Pinch
Pinch

Reputation: 4207

Looks like contentType was a major player here.

Based on an answer by Darin Dimitrov:

   <script>           
       function AddButton() {
           $.ajax({
               url: '@Url.Action("AddChargeCategories")',
               type: "POST",
               contentType: 'application/json',
               data: JSON.stringify({ ChargeID: $("#ChargeID").val(), CategoryIDs: $("#CategoriesBefore").val() })
           }).success(function () { location.reload(true); });
           return false;           
       }       
   </script>

Upvotes: 2

Related Questions