I recently started evaluating ASP.NET MVC. While it is really easy and quick to create Controllers and Views for Models with only primitive properties (like shown in the starter videos from the official page) I didn't find any good way to work with references to complex types. Let's say, I have these Models:
public class Customer {
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public IList<Order> Orders { get; set; }
}
public class Address {
public int Id { get; set; }
public string .....
.....
}
public class Order {
public int Id { get; set; }
public Customer Customer { get; set; }
public string OrderName { get; set; }
.....
}
Note that I don't have foreign keys in the models (like it's typical for LINQ to SQL, which is also used in the sample video) but an object reference.
How can I handle such references in asp.net mvc? Does someone has some good tips or links to tutorials about this problem? maybe including autobinding with complex types.
I would combine everything into my view model:
You should be able to bind your complex objects without too much trouble using some of the input helpers:
The should bind back ok if your action method looks like:
Hal
I prefer to keep my views as 'dumb' as possible, so I like to create custom view models for binding.
In your controller you can map your rich domain objects to the view model's flatter model. For example:
If you're looking for good material on this subject, I recommend ASP.NET MVC View Model Patterns.
You can use Data Transfer Objects for this issue or you can use expand methods on entity - include method in EF -
Nothing is different with primitive properties. If thats not what you mean, correct me then I'll help you again
Thanks
DTO:
NHibernate repository:
View:
With Expand - Include - Model type is 'Order':
With DTO - Model type is 'OrderDTO':
edit:
Okay, first you may want to use FormViewModel for create/edit actions. like this;
Controller:
View: