为什么我的ASP.Net MVC模型没有正确填充?

时间:2014-03-28 16:26:18

标签: json asp.net-mvc-4

我确定我在这里做了一些愚蠢的事情,但我无法弄清楚是什么!

public virtual ActionResult Edit(ContactViewModel contactModel)
{
    var phones = contactModels.Phones; // <-- This works fine
    var emails = contactModels.Emails; // <-- Count is 1, but EmailViewModel data is all blank

    return Json(new { Success = true });
}

型号:

public class ContactViewModel
{
    public long Id { get; set; }

    [Required(ErrorMessage = "Contact Type is required")]
    [Display(Name = "Contact Type")]
    public long ContactTypeId { get; set; }

    [Display(Name = "First Name")]
    [StringLength(50, ErrorMessage = "Maximum length is 50 characters")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [StringLength(50, ErrorMessage = "Maximum length is 50 characters")]
    public string LastName { get; set; }

    public PhoneViewModel[] Phones { get; set; }

    public EmailViewModel[] Emails { get; set; }

    [Display(Name = "Marketing Rep")]
    public long? MarketingRepId { get; set; }
}

public class PhoneViewModel
{
    public long Id { get; set; }
    public long PhoneTypeId { get; set; }
    public string PhoneType { get; set; }
    public string Number { get; set; }
    public bool? ToDelete { get; set; }
}

public class EmailViewModel
{
    public long Id { get; set; }
    public long EmailTypeId { get; set; }
    public string EmailType { get; set; }
    public string Address { get; set; }
    public bool? ToDelete { get; set; }
}
来自Fiddler的Json:

{"Id":"38484","ContactTypeId":"762","FirstName":"First","LastName":"Last",
"Phones":[{"Id":46783,"PhoneType":"Home","PhoneTypeId":3,"Number":"555-5555",
"ToDelete":false}],"Emails":[{"Id":0,"EmailType":"Work","EmailTypeId":1,
"Address":"myemail@gmail.com","ToDelete":false}],"MarketingRepId":"0"}

除了电子邮件之外,一切都正在转移到CustomerViewModel。数组显示1个元素,但是当我在VS中设置断点并检查元素时,一切都为null。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

事实证明,有一个附加到EmailViewModel的模型绑定器,它拦截了进入的数据并对其进行了错误处理,以便它返回一个空模型。

我删除了这个模型绑定器,一切都很好。