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.


Comments:

Very informative post. Thanks nosuchblogger.com for taking the time to share your view with us.

You ought to experience a tournament for just one of the most useful blogs on the web. I’ll recommend this web site!

Hahah, My laptop crashed when I was browsing this site last time I was here. And for the past 2 months I have been looking for this weblog, so thankful I located it once again! :D


Comment Guidelines
See the FAQ for details on the full rules and guidelines. No Spam. Write clearly and thoughtfully - no bad language.