ASP.NET MVC 4 JSON绑定到视图模型 – 嵌套对象错误
发布时间:2020-12-05 04:49:00 所属栏目:asp.Net 来源:互联网
导读:我有json绑定到视图模型的问题.这是我的代码: 部分ViewModels(AddressViewModel有更多的属性): public class AddressViewModel{ [Display(Name = Address_Town, ResourceType = typeof(Resources.PartyDetails))] public st
我有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) 这是我用firebug看到的: 这就是我在VS看到的: 正如你所看到的,普通属性被绑定正确,但我的嵌套对象(国家)是空的.我读了很多不同的文章,我仍然不知道我做错了什么.请帮帮我! 解决方法问题来自于你的action方法参数:[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 ... } (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – Dropzone没有绑定到模型
- asp.net-mvc – 使用MVC3剃刀的ASP.Net图表控件
- asp.net – 如何在C#2.0中的Web.config中加密用户名和密码
- asp.net – 是否有可能过滤SignalR中的接收器?
- asp.net-mvc – 如何继承ASP.NET MVC控制器并仅更改视图?
- asp.net – 我应该使用WebMatrix构建一个真实世界的网站吗?
- asp.net-mvc – 用于测试目的的假开放ID提供程序
- ASP.NET MVC4 Razor模板简易分页效果
- asp.net-mvc – ASP.NET Web Api – 将对象发布到自定义动作
- 在ASP.NET MVC4中是否可以将C#或VB函数标记为Javascript?