简体   繁体   中英

How should I deal with an aggregated model in ASP MVC?

I am learning ASP MVC and I have problem. I have class Company with an aggregated property:

public class Company
{
    public Company()
    {
        Address = new Address();
    }

    public int Id { get; set; }     
    public string Name { get; set; }
    public virtual Address Address { get; set; }
}

And Address class:

public class Address
{       
    public int Id { get; set; }     
    public string Country { get; set; }
    public string City { get; set; }
    ...
}

How should I write edit for this field? I have tried to create control AddressDetail and pass it to UiHint attribute on Address property, but in view i have additional Id property to edit (!?). When I hide it model state in post is not valid because this property is required. Another question is how should repository look like for Company? Should it use AddressRepository somehow or write Address by itself?

Maybe somebody have example of that kind of situation?

One way to tackle this would be to create a view model that combines these fields. You can pass that to the view, and have your controller & repository handle converting it back into your business models. For example:

public class CompanyViewModel
{        
    public int Id { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
    public string City { get; set; }
}

For another example, check out "Pattern 3" here: http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

As long as the Address class has a parameterless constructor (like your company class), the default mvc modelbinder will have no problem handeling your object. It is not a problem, that both your Company class and Address class has an Id property.

MVC will by default assign your inputfields with names like 'Id' and 'Address.Id', which allows for the modelbinder to distinguish between the two properties.

You could register an editor template for your address class in Global.asax, or you could simple make a partial view and pass it Company.Address in your main view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM