我遇到了 json 绑定到视图模型的问题。这是我的代码:
我的 ViewModel 的一部分(AddressViewModel 有更多属性):
public class AddressViewModel
{
[Display(Name = "Address_Town", ResourceType = typeof(Resources.PartyDetails))]
public string Town { get; set; }
[Display(Name = "Address_Country", ResourceType = typeof(Resources.PartyDetails))]
public Country Country { get; set; }
}
public class Country : EntityBase<string>
{
public string Name { get; set; }
protected override void Validate()
{
if (string.IsNullOrEmpty(Name))
{
base.AddBrokenRule(new BusinessRule("CountryName", "Required"));
}
}
}
Javascript:
$(document).on("click", "#addAddress", function () {
var jsonData = {
"Town": $('#txt-Town').val(),
"District": $('#txt-District').val(),
"Street": $('#txt-Street').val(),
"PostCode": $('#txt-PostCode').val(),
"FlatNumber": $('#txt-FlatNumber').val(),
"PremiseName": $('#txt-PremiseName').val(),
"PremiseNumber": $('#txt-Premisenumber').val(),
"Country": {
"Name": $('#txt-Country').val(),
}
};
var addressData = JSON.stringify(jsonData);
$.ajax({
url: '/Customer/SaveAddress',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: addressData,
success: function (result) {
$("#addIndividualAddressDialog").data("kendoWindow").close();
},
error: function (result) {
alert("Failed");
}
});
});
控制器标头:
[HttpPost]
public ActionResult SaveAddress(AddressViewModel addressViewModel)
这是我在萤火虫中看到的:
这就是我在 VS 中看到的:
如您所见,普通属性绑定正确,但我的嵌套对象(国家/地区)为空。我阅读了很多不同的文章,但我仍然不知道我做错了什么。请帮帮我!