ASP.NET MVC 4 JSON绑定到视图模型 – 嵌套对象错误

前端之家收集整理的这篇文章主要介绍了ASP.NET MVC 4 JSON绑定到视图模型 – 嵌套对象错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有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相关文章