Passing two different models to a view with ASP.Net MVC
I'm trying to set up a view that displays two different models. For example, I have a "Details" view that shows details of a customer; which I am passing my customer开发者_StackOverflow model. I also want to have a section on the page under the customer information (I was thinking about using a partial view) that lists their pets (for a vet practice). I tried to set up a partial view and in the dialogue box I indicated to use the "pet" model, but was unsuccessfull in my attempt. Any help would be greatly appreciated.
A partial view would be great for pets list. Just create an strongly typed .ascx as:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PetList>" %>
Then display it from the main page. You may wish to use the same pets list control on another pages.
Create a class that contains the Customer data and the Pet data:
public class CustomerDetailsViewModel
{
public Customer Customer { get; set; }
public IList<Pet> Pets { get; set; }
}
That is your model for the view. Inside the view, use Model.Customer
for your customer data and pass Model.Pets
to your partial view which is strongly-type to IList<Pet>
.
Make a stongly typed view taking a type like
Pair<Customer, Pet> (or Pair(of Customer, Pet)) if using VB
or just pass a
Pair<Customer, Pet>
object in the view data object.
Then pass the Pet object to the partial view.
精彩评论