【发布时间】:2021-09-07 17:50:10
【问题描述】:
我可以将模型从视图中检索到我的脚本,但将其发布到控制器不起作用。 我从 ajax 得到的模型是空的。为什么 ?这是某种类型的问题吗?我不明白为什么,请帮忙。
我的脚本:
$('#addresssendbutton').on('click', function () {
var valdata = $("#serializer").serialize();
console.log(valdata); //This shows me all the data without missing
$.ajax({
type: 'POST',
url: '/Home/SaveClientAddress',
data: { 'clientAddress': valdata },
success: function (response) {
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Adresiniz kaydedildi...',
showConfirmButton: false,
timer: 1500
})
},
error: function (response) {
Swal.fire({
icon: 'error',
title: 'Hata...',
text: response.errormessage,
})
}
});
});
我的控制器:
public async Task<ActionResult> SaveClientAddress(ClientAddress clientAddress)
{
Debug.WriteLine(clientAddress.clientaddress_cityname);
if(!db.ClientAddress.Where(x=>x.client_id == clientAddress.client_id).Any())
{
db.ClientAddress.Add(clientAddress);
await db.SaveChangesAsync();
return Json(new
{
success= true,
error=false
});
}
else
{
return Json(new
{
success=false,
error=true,
errormessage = "Sistemde zaten kayıtlı bir adresiniz var."
});
}
}
编辑: 客户端地址模型:
[Table("clientaddress_tbl")]
public class ClientAddress
{
[Key]
public int clientaddress_id { get; set; }
[ForeignKey("Client")]
public int? client_id { get; set; }
[Required]
public string clientaddress_cityname { get; set; }
[Required]
public string clientaddress_districtname { get; set; }
[Required]
public string clientaddress_neighborhoodname { get; set; }
[Required]
public string clientaddress_streetname { get; set; }
[Required]
public string clientaddress_apartmentnumber { get; set; }
[Required]
public string clientaddress_buildingnumber { get; set; }
[Required]
public string clientaddress_addressdescription { get; set; }
public virtual Client Client{ get; set; }
}
还有console.log(valdata):
clientaddress_cityname=istanbul&clientaddress_districtname=umraniye&clientaddress_neighborhoodname=site&clientaddress_streetname=evren&clientaddress_buildingnumber=54&clientaddress_apartmentnumber=9&clientaddress_addressdescription=xxxxxx&client_id=1
我从会话中获取了 client_id,并且模型中除了 clientaddress_id 之外没有任何空字段。
【问题讨论】:
-
如果您的
data { clientAddress: valdata }与您的班级ClientAddress不匹配完全,则它将是null。获取 any 帖子首先使用基本数据,例如id,然后是一个简单的类(可能 ClientAddress 很简单),但只有一个 ID 和一个字符串属性 - 在具有嵌套类的复杂类之前 -
请包括您的 ClientAddress 模型和来自 console.log(valdata) 的响应;
-
@freedomn-m 我正在使用 Code-First,除了模型中的 clientaddress_id 字段之外,我正在传递所有数据。应该没问题吧?
-
@CarstenLøvboAndersen 好的,等一下。
-
@CarstenLøvboAndersen 我已经包括了这些。
标签: c# ajax asp.net-mvc