asp.net mvc - Ajax request with list of javascript objects failing -
this question asked lot, none of answers worked me. i'm trying send list of objects controller in asp mvc 5. i'm josn.stringify
'ing list, , trying receive list.
i sure hope it's not stupid typo i'm missing...
well did find typo (funny how writing things down helps), isn't problem. ajax calling "sale" controller "sales". fixed it, still same problem. (added picture @ end).
edit
i changed ajax to:
$('#complete-sale').on('click', function () { alert("in complete sale"); var itemsincart = json.stringify(shoppingcart.getitemsincart()); alert("itemsincart: " + itemsincart); $.ajax({ type: "get", url: "/sales/completesale", // method calling contenttype: "application/json; charset=utf-8", data: { 'itemsincart': itemsincart }, datatype: "json", success: function (result) { alert("sale complete succeeded" + result[0]); additemtocart(result[0]); }, error: function (result) { alert("failed complete sale request " + result[0]); } }); });
the request url shown in developer tools now:
http://localhost:52459/sales/completesale?itemsincart=[{"itemid":1,"quantity":"1","price":3.5}]
which seems should right. changed controller return return view("hello")
comes back.
model:
public class itemincart { [key] public int itemid { get; set; } public virtual variety variety { get; set; } public int quantity { get; set; } public virtual inventoryitem inventoryitem { get; set; } public double price { get; set; } public virtual variety price { get; set; } }
controller (sales.cs
):
[httpget] public actionresult completesale(list<itemincart> itemsincart) { return view(); }
ajax:
$('#complete-sale').on('click', function () { alert("in complete sale"); itemsincart = shoppingcart.getitemsincart(); stringifieditemsincart = json.stringify({ 'itemsincart': itemsincart}); alert("stringified: " + stringifieditemsincart); $.ajax({ type: "get", url: "/salescompletesale", // method calling contenttype: "application/json; charset=utf-8", data: stringifieditemsincart, datatype: "json", success: function (result) { alert("sale complete succeeded" + result[0]); additemtocart(result[0]); }, error: function (result) { alert("failded complete sale request " + result[0]); } }); });
i came across problem other day, , can little confusing, in case method signature involves list of view models.
json.stringify()
seems work great me post
data , maybe else can explain why is, get
requests, not right solution.
the problem had requesting url list of int
, , either coming null
or erroring. needed create query string such: ?selectedids=1&selectedids=2&selectedids=3
.
Comments
Post a Comment