我遇到了将json绑定到视图模型的问题。这是我的代码:
我的ViewModels的一部分(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中看到的:
如您所见,普通属性绑定正确,但是我的嵌套对象(国家/地区)为空。我读了很多不同的文章,但我仍然不知道自己在做什么错。请帮帮我!
问题出在您的操作方法参数上:
[HttpPost]
public ActionResult SaveAddress(AddressViewModel addressViewModel)
使用时JSON.stringify()
,您将字符串发送到控制器,而不是对象!因此,您需要做一些工作以实现您的目标:
1)更改操作方法参数:
[HttpPost]
public ActionResult SaveAddress(string addressViewModel)
2)将字符串反序列化为一个对象-即AddressViewModel:
IList<AddressViewModel> modelObj = new
JavaScriptSerializer().Deserialize<IList<AddressViewModel>>(addressViewModel);
因此,您的最终操作方法应如下所示:
[HttpPost]
public ActionResult SaveAddress(string addressViewModel)
{
IList<AddressViewModel> modelObj = new
JavaScriptSerializer().Deserialize<IList<AddressViewModel>>(addressViewModel);
// do what you want with your model object ...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句