Joe
Joe

Reputation: 2107

How do I populate my view model?

I'm using MVC to build a basic application for use in a veterinary clinic. The application has a screen where staff can see a pet's appointment history and add appointments.

The history portion is wired up and works fine. I see a list of all previous appointments and can navigate into each appointment to see its details.

The problem is adding a new appointment. The Edit view of the Pet controller has the following action link:

@Html.ActionLink("Add Appointment", "Create", "Appointment", new { id = Model.Id }, null)

This ActionLink passes the Pet's Id from the current model to the Create action of the Appointment controller. The pet Id is necessary because that's how the db connects pets and appointments.

The view model used in the Create view of the Appointment controller has Pet and Appointment properties.

How do I populate the properties of the view model? The Appointment is going to be created with the Create view of the Appointment controller but I still need to display various Pet properties on the Create screen (name, age, species, etc.). Those are in the Pet property of the view model. How do I go from the id passed into the ActionLink to hydrated Pet object in the view model? I don't think I need another trip to the database because all the Pet properties I need are in the model used for the Edit view of the Pet controller

Thanks!

MVC 4 RC

Upvotes: 0

Views: 272

Answers (2)

getit
getit

Reputation: 621

One you receive a response from the server, your db connection is closed. If you redirect to another page, you'll have to make another db call to load whatever it is you need.

Upvotes: 0

Gabe
Gabe

Reputation: 50493

You populate your Model from within a Controller Action.

public ActionResult Create(string id){

   MyModel myModel = new MyModel();
   myModel.Foo = "Bar";
   return View(myModel);

}

You could extract it to populate on a service layer with a service call that happens inside your controller. It would then pass back a model that would be sent to the View.

public ActionResult Create(string id){

   // Some service inteface to interact with the data store to populate model
   MyModel myModel = service.GetMyModel();
   return View(myModel);

}

Upvotes: 1

Related Questions