开发者

Passing form data to controller method - child properties are not getting filled in

My app is using JavascriptMVC on the client side, and ASP MVC is basically functioning only as a REST service. Here's a typical controller method:

public JsonResult Update(CustomerDto dto)
{
  var repository = Factory.NewCustomerRepository())
  // ... Convert DTO back to entity and save changes
  return Json(dto);
}

The problem is, my CustomerDTO contains some properties that aren't getting converted from the form data into the objects that they should be. For example, PhoneNumbers:

public class CustomerDto
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public PhoneNumberDto[] PhoneNumbers { get; set; }
    // ... more properties
}
public class PhoneNumberDTO
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public string Label { get; set; }
    public string Number { get; set; }
}

In the controller action, PhoneNumbers will have the correct number of elements in the array, but each object will have only null/default values. I've verified that the request is sending all of the appropriate form data:

开发者_StackOverflow中文版
Id          26
FirstName   A
LastName    Person
MiddleName  Test
PhoneNumbers[0][CustomerID  26
PhoneNumbers[0][Id] 5
PhoneNumbers[0][Label]  Mobile
PhoneNumbers[0][Number] (555)555-5555
PhoneNumbers[1][CustomerID  26
PhoneNumbers[1][Id] 8
PhoneNumbers[1][Label]  Home
PhoneNumbers[1][Number] (654)654-6546

Any ideas on what could be going on? Am I just wrong in thinking that MVC3 can map nested objects from the form values automatically? Thanks for any help!


Actually the request should look like this if you want the default model binder to successfully bind those values (notice PhoneNumbers[0].CustomerID instead of PhoneNumbers[0][CustomerID]):

Id                          26
FirstName                   A
LastName                    Person
MiddleName                  Test
PhoneNumbers[0].CustomerID  26
PhoneNumbers[0].Id          5
PhoneNumbers[0].Label       Mobile
PhoneNumbers[0].Number      (555)555-5555
PhoneNumbers[1].CustomerID  26
PhoneNumbers[1].Id          8
PhoneNumbers[1].Label       Home
PhoneNumbers[1].Number      (654)654-6546

You may take a look at the following blog post for the wire format used for collections.

As an alternative you could use JSON requests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜