How to send simple id (jquery ajax) to Action Method in asp.net mvc
I have a category dropdown in which I write the code for this onchange event:
function onChange() {
$.ajax(
{
url: '/Home/GetProducts/',
type: 'POST',
data: JSON.stringify({ID:$("#Category").val()}),
//contentType:"application/json; charset=utf-8",
dataType: "json",
success: function (data){
var jsonres = "";
$.each(data, function (i, variant) {
jsonres += '<option value="' + variant.ID + '">' + variant.Name+ '</option>';
});
$("#product").html(jsonres);
}
, error: function () { alert('Error'); }
});
}
and my action method:
[HttpPost]
public ActionResult GetProducts(int? ID)
{
var res = _teacherUow.GetProducts(ID.GetValueOrDefault()).Select(x => new { x.ID, x.Name }).ToList();
return Json(new { Result = true, data = res }, JsonRequestBehavior.AllowGet);
}
my view code:
@Html.DropDownList("Category", new SelectList(ViewBag.Category, "ID", "Name"), new { id = "Category", onchange = "onChange()" })
<select data-val="true" id="product" name="product">
</select>
Now I have three problems
1 - get null in the parameter of the action method
Json result:
{"Result":true,"data":[{"ID":1,"Name":"xxx"},{"ID":3,"Name":"yyyy"}]}
2- but the value and text of the dropdown list of items is 'undefined'
3- create empty dropdown for product field using html helper (for fill data element by Ajax request) can anyone help me?
source to share
Problem 1: change
data: JSON.stringify({ID:$("#Category").val()}),
to
data: { ID: $("#Category").val()},
Problem 2: you are returning an object containing 2 properties Result
and data
so the success callback should be
$.each(data.data, function (i, variant) {
however you are not using the property Result
and it seems pointless, so you could just use
[HttpGet] // Change this (its a get not a post!)
public ActionResult GetProducts(int? ID) // assume this was a typo
{
var res = _teacherUow.GetProducts(ID.GetValueOrDefault()).Select(x => new { x.ID, x.Name }); // no need to call ToList()
return Json(res, JsonRequestBehavior.AllowGet);
}
and in the script use your original code except change type: 'POST',
-type: 'GET',
Problem 3: to create an empty dropdown property binding Project
use
@Html.DropDownFor(m => m.Project, new SelectList(IEnumerable.Empty<T>))
or assign IEnumerable.Empty<T>
to package property view
Note. I suggest the following changes to your script
$('#Category').change(function() { // remove the `onChange` attribute in the helper
$('#Project').empty(); // ensure any existing options removed
$.getJSON('@Url.Action("GetProducts", "Home")', { ID: $(this).val() }, function (data) {
$.each(data, function(index, item) {
var option = $('<option></option>').val(item.ID).text(item.Name);
$('#Project').append(option);
});
});
});
source to share