Garry Pilkington


Application Developer
Liverpool, UK

October 2009 - Posts

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%>
Posted: Oct 20 2009, 09:29 AM by capgpilk | with 12 comment(s)
Filed under: , , ,
Unit Testing Videos

The Learn Visual Studio.net website has just published a new series on unit testing, covering an introduction to unit testing, using MSTest, and NUnit. These are always good sources of practical information to help you get up to speed on anything .net. Go check them out.

More Posts