NoName NoName - 4 months ago 37
Ajax Question

populate listbox when dropdownlist changed with jquery in asp mvc

I have a list of categories in a drop-down box in my form. I would like to populate a different select list, based on the selected item of the category drop-down, without post backs and all that.

I created a method in my controller that does the work:

[HttpPost]
public ActionResult GetItemByCategoryId(int category_id)
{
var itemsobject = DB.items.Where(s => s.category_id == category_id).ToList();
SelectList item_id = new SelectList(itemsobject, "item_id", "item_name");
ViewBag.item_id = item_id;
return Json(itemsobject, JsonRequestBehavior.AllowGet);
}


Here is my view:

<div class="form-group">
<label class="control-label col-md-4">category name</label>
<div class="col-md-4">
@Html.DropDownListFor(a => a.category_id, (SelectList)ViewBag.category_id)
</div>
</div>

<div class="form-group">
<div class="col-md-4">
<div class="col-md-4" id="mydiv">
</div>
</div>
</div>


And, here is a Javascript function that fires on drop-down list change event and does the ajax call to the action method that returns the JSON result.

<script language="javascript" type="text/javascript">
$(function () {
$("#category_id").change(function() {
c = $(this).val();
alert(c);
$.ajax({
url: "@Url.Action("GetItemByCategoryId", "Category")",
data: { "category_id": c },
cache: false,
DataType: 'json',
type: "POST",
success: function (data) {
$("#mydiv").text(data[0].Text);
},
error: function () {
alert("failed");
}
});//end ajax
});//end change event
});//end document loading
</script>


But, this does not work. I just get a popup failed for my alert.
Can you show me how to achieve this?

Answer

the problem was in the action

return Json(itemsobject, JsonRequestBehavior.AllowGet);

it must return selectList in the json

return Json(item_id, JsonRequestBehavior.AllowGet);
Comments