Create View Model

Hello 

I have just stepped into MVC . And I am in the need that I want to create a strongly typed view( To Save  records)  from multiples entities Let me explain you the complete scenario .

I have following Entities

School: id ( Identity),Name, NumberOfStudents, ContactId ( FK), ImageId (FK). 

Contact : Id ( Identity ) ,Address, City,State,Email 

Image :Id (identity) ,ImagePath

I need to create a view where I can ask user to fill detail about school .Contact details should also be filled on the same view. and I am to save this entire info along with valid foreign key so that I may retrieve data accordingly in other views wherever
needed.

I googled and came to know that ViewModels are there to do this job but I really could not get any idea how to create a view from multiples entities by supplying only those fields that are to render by a view. Also do let me know how to save complete ViewModel
in different entities/tables.

It would be very appreciated if you could help in this .

Thanks and Regards.

The in most simple of cases, you’ll just need to create a basic class that contains the necessary properties that you need and then populate it with your entities. For instance, a School View Model might look something like this :

public class SchoolSummaryViewModel
{
     // Store the actual School
     public School School { get; set; }
     // Store all the contacts for this School
     public List<Contact> Contacts { get; set; }
     // Store all of the images associated to the school
     public List<Images> Images { get; set; }

     public SchoolSummaryViewModel()
     {

     }
}

So then within your Controller Action, you would just want to populate all of these fields accordingly :

public ActionResult ViewSchool(string id)
{
      // Create an instance of your ViewModel
      var model = new SchoolSummaryViewModel();

      // Open your context to populate it
      using(var context = new YourContextHere())
      {
             // Populate the school
             model.School = context.Schools.FirstOrDefault(s => s.Id == id);

             // Now that you have the school, get the other associated properties
             model.Contacts = context.Contacts.Where(c => c.Id == model.SchoolId.ContactId).ToList();
             model.Images = context.Images.Where(i => i.Id == model.SchoolId.ImageId).ToList();
      }

      // Send your View Model to the View
      return View(model);
}

and then just wire up your View to accept your ViewModel :

@model YourApplication.ViewModels.SchoolSummaryViewModel

Then if you wanted to output all of your information, you could just access it by the properties :

School Name : @Model.School.Name
<br />

<!-- Output each of your Contacts (rough example) -->
@foreach(var contact in Model.Contacts)
{
      Address: @contact.Address
}

<!-- Output each of your Image (rough example) -->
@foreach(var image in Model.Images)
{
      <img src="@image.ImagePath" />
}

Leave a Reply