3

Most of the samples I see online are showing CRUD with single entity class.

If I were to create a CRM application and one of the views needs to display customer information in read only mode and on the same page, display Contacts, Notes, Attachments, Addresses, how should the controller pass these different entities to the view?
Should I be creating another model class which will be a container for the various other entities and populate that model class with the various entities and pass back to the View.

In another scenario, say I wanted to display the Customer entity in Edit mode and the View has dropdowns for Customer Active Status, Customer StateCode, Customer Satisfaction dropdowns. Each of these dropdowns have other entity collections that are bound to them. So, again in this scenario, how should a controller pass back the model which has all these entities and not just Customer entity.

I continue to read on ViewModel pattern and I think this may be the way to go but would certainly appreciate more guidance and pointers.

Mathieu
  • 4,449
  • 7
  • 41
  • 60
Pratik Kothari
  • 2,446
  • 2
  • 32
  • 54

1 Answers1

2

You're exactly right. Create a ViewModel which represents the objects which your page requires.

Your first scenario could be something like the following:

public class CustomerInformationViewModel
{
    IEnumerable<Contact> Contacts { get; set; }
    IEnumerable<Note> Notes { get; set; }
}

Populate these in your controller and then access them in your view.

@foreach (var contact in Model.Contacts)
{
    @Html.DisplayFor(c => c.Name)
}

For your second scenario, exactly the same. You want to bind to your customer properties but you also want some additional collections for drop down lists.

public class CustomerEditViewModel
{
    Customer Customer { get; set; }
    IEnumerable<Status> StatusOptions { get; set; }
    IEnumerable<StateCode> StateCodeOptions { get; set ; }
}

Just keep in mind that you will need to re-populate these collections in your controller if you discover that your ModelState is invalid at the controller.

David Spence
  • 7,999
  • 3
  • 39
  • 63
  • Thanks @Spencerooni. Are there any real-world examples or source code samples you can point to? That would be very helpful. – Pratik Kothari Sep 29 '12 at 15:51
  • Here is an [example using MVC2](http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3fundamentals_topic7.aspx) from MSDN. Including two other related answers which may be of help [example 1](http://stackoverflow.com/a/4579618/609176) [example 2](http://stackoverflow.com/a/9882809/609176) – David Spence Sep 29 '12 at 16:11