我想在 Asp.Net MVC 中通过 Ajax 提交页面输入。
JQuery Ajax json 数据不为 null(在 Console.log() 中检查),但它将 json 字符串 null 传递给 Controller 操作。 Controller 操作将对象视为字符串:
类(class):
public int ID { get; set; }
public string ProductName { get; set; }
public int CategoryID { get; set; }
public int BrandID { get; set; }
public int Price1 { get; set; }
public string Exchange { get; set; }
public bool State { get; set; }
Controller :
[HttpPost]
public ActionResult AddProduct(string data)
{
//string data comes null here
}
JQuery:
var xy ={
"data": {
CategoryID: categoryID,
BrandID: brandID,
ProductName: productName,
Price1: price1,
ExchangeName: exchangeName,
State: state
}
};
console.log(JSON.stringify(xy))
$.ajax({
url: "/Products/AddProduct/",
type: 'POST',
data: JSON.stringify(xy),
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText)
}
});
console.log 的输出(JSON.stringify(xy)):
{"data":{"CategoryID":"63","BrandID":"1","ProductName":"pname","Price1":"199","State":"1"}}
我检查了很多答案,但无法找出我的问题。 感谢您的帮助。
最佳答案
在操作中您需要声明所有参数:
[HttpPost]
public ActionResult AddProduct(int CategoryID, int BrandID, string ProductName, double Price1, string ExchangeName, int State)
{
}
并传递这样的数据:
$.ajax({
url: "/Products/AddProduct/",
type: 'POST',
data: {CategoryID: categoryID,
BrandID: brandID,
ProductName: productName,
Price1: price1,
ExchangeName: exchangeName,
State: state},
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText)
}
});
关于jquery - Ajax 向 Controller 操作发送空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44264869/