I have been attempting to use AJAX to post data when a dropdown selection is changed, but for some reason, the call is not reaching the controller.
I have even tried setting a breakpoint in the controller to debug, but the AJAX call still does not post back successfully.
Here is the HTML code:
<div class="col-md-6 col-sm-6">
@Html.DropDownList("CategoryId",null,new { @class = "form-control col-md-7 col-xs-12 ", required = "required", id = "CategoryDropDown",
onchange="GetSubCategory()" })
</div>
<div class="col-md-6 col-sm-6">
<select id="SubCategory" class="form-control col-md-7 col-xs-12" required="required"></select>
</div>
Below is the AJAX code being used:
function GetSubCategory() {
var stateId = $("#CategoryDropDown").val();
$.ajax
({
url: '/Home/GetSubCategory',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId:+stateId
}),
success: function (result) {
$("#SubCategory").html("");
$.each($.parseJSON(result), function (i, SubCategory) {
$("#SubCategory").append($('<option></option>').val(SubCategory.Value).html(SubCategory.Text))
})
},
error: function () {
alert("Oops! Something went wrong..")
},
});
}
And here is the code snippet from the controller:
[HttpPost]
public ActionResult GetSubCategory(int stateId)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(Logics.SubCategory(MainCatId));
return Json(result, JsonRequestBehavior.AllowGet);
}
I expected that the AJAX call would work smoothly and I would be able to populate the sub-dropdown list using this method.