I have a ViewModel looks like
namespace HealthBox_WebCore_V1.ViewModel
{
public class ProductViewModel
{
public MST_ProductViewModel MST { get; set; }
public List<int> FoodsID { get; set; }
}
}
And I have a ajax function like this
function post() {
/* var url = $("#CreateProductForm").attr("action");*/
var data = $("#CreateProductForm").serialize();
var FoodsIDVal = [];
$("select[name='FoodsID']").each(function () {
var values = $(this).val();
FoodsIDVal.push(values);
});
var ViewModel = {
"MST":data,
"FoodsID":FoodsIDVal
};
console.log(ViewModel);
$.ajax({
type: "POST",
url: "CreateProduct",
data: JSON.stringify(ViewModel),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
},
error: function () {
}
});
}
If I use this way, I get this result in Controller
FoodsID get null.
But if I use this,
function post() {
/* var url = $("#CreateProductForm").attr("action");*/
var data = $("#CreateProductForm").serialize();
var FoodsIDVal = [];
$("select[name='FoodsID']").each(function () {
var values = $(this).val();
FoodsIDVal.push(values);
});
var ViewModel = {
MST:data,
FoodsID:FoodsIDVal
};
console.log(VM);
$.ajax({
type: "POST",
url: "CreateProduct",
data: ViewModel,
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
here is the result in controller
I just want to post these two object to Controller 『MST and FoodsID』 I also try add attr [FromBody] or other way as I can search in Google, but can't find a way to slove this problem. Please help, many thanks
CodePudding user response:
You only need to add [FromBody]
to the action and use the first ajax,here is a demo:
action
[HttpPost]
public IActionResult CreateProduct([FromBody]ProductViewModel productViewModel)
{
return RedirectToAction("Index");
}
ajax:
function post() {
/* var url = $("#CreateProductForm").attr("action");*/
var data = $("#CreateProductForm").serialize();
var FoodsIDVal = [];
$("select[name='FoodsID']").each(function () {
var values = $(this).val();
FoodsIDVal.push(values);
});
var ViewModel = {
"MST":data,
"FoodsID":FoodsIDVal
};
console.log(ViewModel);
$.ajax({
type: "POST",
url: "CreateProduct",
data: JSON.stringify(ViewModel),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
},
error: function () {
}
});
}
If you still cannot get FoodsID,try to check the data of FoodsIDVal
in ajax.