Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial Views in MVC

I'm brand new to MVC and have just come across a scenario that I need some help with.

I'll just briefly outline my scenario as if it were a Web Forms application that I'm far more familiar with.

SCENARIO:

I have a homepage which lists the most recent 10 blog posts, along with an 'Archive Tree' (listing the years/months in chronological order, with links to each of the blog entries made in those years/months).

I create this 'Archive Tree' as a User Control and output that user control on my homepage.

I also output this Archive Tree user control down the side of my main blog page - the blog page renders the details for just a single blog post.

I also want to re-use this Archive Tree control across a couple of other pages in my web application.

MVC:

I have a 'PhotoController' Controller, which has an ActionResult Method responsible for getting the details of the selected Photo Blog post (id).

I want to include a Partial View (the Archive Tree, that will render multiple records) on my Photo Blog page, that will loop through multiple photo records (List<Photo>).

I could create a View Model that consists of a 'Photo' property (for rendering the single photo blog record details) and a 2nd property called 'PhotoArchive', which is a List<Photo>.

My concern with this approach though is that, when I come to re-use this 'Archive Tree' Partial View on some of the other sections across the site, I won't necessarily be wanting to pass through that same View Model (that contains both 'Photo' and 'PhotoArchive' objects) to the parent view. For example, my homepage will not need to pass through a 'Photo' object to the view that renders the homepage, but I still want to output my 'Archive Tree' Partial View amongst the rest of the HTML on my homepage.

I'm expecting there is a simple solution to this which I just don't know at the moment being so new to MVC.

like image 707
marcusstarnes Avatar asked Oct 14 '22 20:10

marcusstarnes


1 Answers

There's a few ways to achieve this:

You could just use Html.RenderAction() http://www.asp.net/mvc/videos/aspnet-mvc-2-render-action

Or you could use different view models

class HomePageViewModel {
  IEnumerable<Blog> PhotoArchive { get; set; }
}
class BlogPageViewModel {
  IEnumerable<Blog> PhotoArchive { get; set; }
  Blog Photo { get; set; }
}

and pass the PhotoArchive property when calling Html.RenderPartial("view", model.PhotoArchive)

Or you could use and interface

interface IMyViewPage {
  IEnumerable<Blog> PhotoArchive { get; set; }
}
class MyViewModel : IMyViewPage{
  //...
  Blog PhotoBlog { get; set; }
}

and Model.RenderPartial("view", model)

like image 122
David Glenn Avatar answered Nov 15 '22 04:11

David Glenn