Multiple Strongly Typed Partial Views in MVC

Creating strongly typed views with the ASP.Net MVC framework is really easy, but what if you want to have multiple types on the same view? One way to achieve this is to create partial views for each type and creating a combined view model. Then the view will inherit this combined view model and each partial view will inherit from its component types.

In the following simple example I have a view which itself displays two partial views. This view inherits from a type I have called CombinedViewModel.

The hosting view

   <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
   Inherits="System.Web.Mvc.ViewPage<CombinedViewModel>" %>
   ...
    
   
   <asp:Content ID="Content1" ContentPlaceHolderID="MainContent"
   runat="server">
        
   <% Html.RenderPartial("PartialView1", ViewData.Model.Header); %>
   <% Html.RenderPartial("PartialView2", ViewData.Model.Detail); %>
    
  </asp:Content>

 

The controller passes the types in to the CombinedViewModel.

public ActionResult Detail(int id)
 {
  Header header = DataRepository.GetHeader(id);
  List<Detail> detail = DataRepository.GetDetail(id);
 
  CombinedViewModel viewData = new CombinedViewModel(header, detail);
 
  return View(viewData);         
 }

The CombinedViewModel

public class CombinedViewModel
{
 public Header  Header { get; private set; }
 public IEnumerable<Detail> Detail { get; private set; }  
 
public JobDetailViewModel(Header header, IEnumerable<Detail> detail)
{
 Header = header;
 Detail= detail;
}
}

 

So now each of the partial views can access the types they need.

The PartialViews

<%@ Control Language="C#"

Inherits="System.Web.Mvc.ViewUserControl<TestApp.Models.Header>" %>

<%= Model.CustomerTitle%>

<%@ Control Language="C#"

Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<TestApp.Models.Detail>>" %>

<%= Model.OrderNumber%>

8 Comments

Comments have been disabled for this content.