Let’s say that you have a website that has certain “UI snippets” that will be reused across multiple pages. A site layout page could help you with this, but let’s say that (a) you won’t need to reuse these sections across all pages and/or (b) these snippets will be rendered in different parts of the markup, depending on the page.
One way to solve that problem is to create a partial and call it specifically from each page where you want it to be rendered. However, let’s say that the partial needs some business data (from the controller). Now the partial-only solution is not that practical.
An alternative would be to add it to the view model object you’re sending back from the page’s controller action and pass it on to the partial. But this means you’ll have to add it to each controller action providing the view model for each page in which you want to add the snippet. So you can see why this is not very DRY. You need a better solution.
Enter Html.RenderAction()
What RenderAction() allows you to do is to call a separate controller action/View from your original View. With this approach you can move the snippet’s business logic to a separate controller/action (which can be unit/integration tested on its own), and create its own View to render the snippet’s content. Then, all you need to do is to call Html.RenderAction() from the page in which you want to inject the snippet.
For example, let’s suppose that we want a little snippet in our website that shows up a summary of the current logged-in user (Name, gender, last time logged in, etc.) If we wanted to use the Html.RenderAction() approach to solve handle this situation, first you’d want to create a controller/action. For example:
public class UserController : Controller
{
[ChildActionOnly]
public ViewResult SummarySnippet()
{
var model = getUserSummaryInfo(); // builds ViewModel object
return View(model);
}
}
(*Note the ChildActionOnly attribute – it tells MVC that this action can only be called when injected from another page. I.e., it cannot be accessed directly by browsing to it).
This action uses the default view (SummarySnippet.cshtml if you’re using razor), in which you will have the markup for the snippet (not shown here). At this point, you’re pretty much ready to use this snippet in any page you want. All you’ll need to do is call Html.RenderAction in your appropriate page’s markup. For example:
@{Html.RenderAction("SummarySnippet", "User");}
Tags: MVC