javascript - how to post simple ID (jquery ajax) to Action method in asp.net mvc -
i have category drop downwards list write blow code in it's 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 action method :
[httppost] public actionresult getproducts(int? id) { var res = _teacheruow.getproducts(id.getvalueordefault()).select(x => new { x.id, x.name }).tolist(); homecoming json(new { result = true, info = 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 have 3 problem
1-in action method parameter receive null
the json result :
{"result":true,"data":[{"id":1,"name":"xxx"},{"id":3,"name":"yyyy"}]} 2- value , text of product drop downwards list fellow member 'undefined'
3- create empty dropdown list product field html helper(for fill info fellow member ajax request) can please help me?
issue 1: change
data: json.stringify({id:$("#category").val()}), to
data: { id: $("#category").val()}, issue 2: returning object containing 2 properties result , data success callback should
$.each(data.data, function (i, variant) { however not using result property , seems pointless anyway utilize
[httpget] // alter (its not post!) public actionresult getproducts(int? id) // assume typo { var res = _teacheruow.getproducts(id.getvalueordefault()).select(x => new { x.id, x.name }); // no need phone call tolist() homecoming json(res, jsonrequestbehavior.allowget); } and in script utilize original code except alter type: 'post', type: 'get',
issue 3: create empty dropdown bound property project use
@html.dropdownfor(m => m.project, new selectlist(ienumerable.empty<t>)) or assign ienumerable.empty<t> view handbag property
note suggest next changes script
$('#category').change(function() { // remove `onchange` attribute in helper $('#project').empty(); // ensure existing options removed $.getjson('@url.action("getproducts", "home")', { id: $(this).val() }, function (data) { $.each(data, function(index, item) { var alternative = $('<option></option>').val(item.id).text(item.name); $('#project').append(option); }); }); }); javascript jquery ajax asp.net-mvc
No comments:
Post a Comment