I am trying to pass an object using JavaScript to a controller.
I have used two parameters _amount
and _total
but the values are empty in the controller on postback. Any ideas why I can't get the values? Also if I want to get the _data
which is an object containing different values, how will I achieve it?
var itemsCart=toys.cart._items;
$.ajax({
url: '@Url.Action("SuccessView", "Home")',
type: 'POST',
data: itemsCart,
success: function (response) {
alert(response);
},
error: function (xhr, ajaxOptions, throwError) {
alert(xhr.responseText);
}
});
Controller:
public IActionResult SuccessView(List<ProductViewModel> products)
{
return View();
}
View Model:
public class ProductViewModel
{
public string _amount { set; get; }
public string _total { set; get; }
}
And a screenshot of the object from the website:
Sounds like the problem is your parameter is declared as products
, but your AJAX data
parameter name did not match with controller action parameter name. Try using this setup instead:
JS
$.ajax({
url: '@Url.Action("SuccessView", "Home")',
type: 'POST',
data: { products: itemsCart },
traditional: true,
success: function (response) {
alert(response);
},
error: function (xhr, ajaxOptions, throwError) {
alert(xhr.responseText);
}
});
Controller Action
[HttpPost]
public IActionResult SuccessView([FromBody] List<ProductViewModel> products)
{
// do something
return new JsonResult("OK");
}
Note that since your AJAX call defined as type: POST
, you must apply [HttpPost]
attribute to the controller action.
Related issue:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
Replace
data: { products: itemsCart }
with
data: ({ products: itemsCart })
Controller:
public IActionResult SuccessView(ProductViewModel products)
{
//return View();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.