[英]MVC controller parameters always null
我的ajax代碼
function gonder() {
var params = {
DonationInfo: {
name: $('#name').val(),
lastname: $('#lastname').val(),
phone: $('#phone').val(),
type: $('#type').val(),
amounth: $('#amounth').val(),
quentity: $('#quentity').val()
}
};
$.ajax({
url: '@Url.Action("Index", "Benafactor")',
type: 'POST',
async: true,
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
alert(data.success);
$('#target').html(data);
},
error: function () {
alert("error");
}
});
}
我的控制器
[System.Web.Http.HttpPost]
public ActionResult Index([FromBody] Mymodel data)
{
return Json(new { success = true });
}
我也嘗試過字符串
這是Mymodel
public class Mymodel
{
public string name { get; set; }
public string lastname { get; set; }
public string phone { get; set; }
public string type { get; set; }
public string amounth { get; set; }
public string quentity { get; set; }
}
我努力嘗試,尋找所有相同的問題,但對我沒有任何幫助,請幫助我可以在請求有效負載中看到數據,但無法將參數輸入控制器
當將對象( params)
序列化為json時,在代碼params
中,mvc ActionResult
參數模型( Mymodel
)和對象( params)
結構必須是相同的結構,而Mymodel
不是相同的結構。 使其相同將解決問題
var params = {
name: $('#name').val(),
lastname: $('#lastname').val(),
phone: $('#phone').val(),
type: $('#type').val(),
amounth: $('#amounth').val(),
quentity: $('#quentity').val()
};
用這個 :
var params = {
name: $('#name').val(),
lastname: $('#lastname').val(),
phone: $('#phone').val(),
type: $('#type').val(),
amounth: $('#amounth').val(),
quentity: $('#quentity').val()
}
對於復雜的對象,使用變量比將其包含在ajax方法中更好
JSON.stringify不是必需的data: params.DonationInfo
function gonder() {
var data= {
name: $('#name').val(),
lastname: $('#lastname').val(),
phone: $('#phone').val(),
type: $('#type').val(),
amounth: $('#amounth').val(),
quentity: $('#quentity').val()
};
$.ajax({
url: '@Url.Action("Index", "Benafactor")',
type: 'POST',
async: true,
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
alert(data.success);
$('#target').html(data);
},
error: function () {
alert("error");
}
});
}
您的控制器將如下所示
[HttpPost]
public ActionResult Index(Mymodel data)
{
return Json(new { success = true });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.