ASP.NET MVC2 RenderAction
I found this useful feature in ASP.NET MVC2 recently and thought it worth a quick mention. First off, the problem was that I wanted to render a section of the page - i.e. a right-hand info section that isn't really part of the main content of the page. Then on pages that I want to display this section, I'd have to populate the View model with the relevant data, which doesn't feel quite right.
One option was to create a html helper method. But as it was a fair chunk of html, it's a bit horrible having to write this in C#.
Another option was to make this an ajax call, which would be easy enough to hook up with jquery. But clients with javascript disabled, or search engines, wouldn't 'see' this content.
Then I found the RenderAction extension method, which is new in MVC2:
<% Html.RenderAction("Action", "Home"); %>
And the controller is simply:
public class HomeController : Controller {
[ChildActionOnly]
public ActionResult Action() {
return View();
}
}
Very neat - I then found Mr Haack's post explaining the new methods. Read Phil's post for all the exciting details.
