Question

I've recently started playing with MVC4, and i'm now on to partial views.

I currently have a controller like so:

public class BlogController : Controller
{
    [ChildActionOnly]
    public ActionResult MostRecent()
    {
        ...
    }
}

And then I call that from any one of my views using the following line:

 @{ Html.RenderAction("MostRecent", "Blog"); }

Is it possible to do something like this:

public static class PartialHelper
{
    public static string RenderMostRecent()
    {
        return notsurewhat.RenderAction("MostPopular", "Blog");
    }
}

so that in my code all i have to call is:

@PartialHelper.RenderMostRecent()

That way I can change the controller / action at any point and I don't have to update everywhere that calls that partial view.

Open to ideas if there is a much easier way to do this!

Thanks

Was it helpful?

Solution

You could write it as an extension method to the HtmlHelper class:

using Sysem.Web.Mvc;
using Sysem.Web.Mvc.Html;

public static class PartialHelper
{
    public static void RenderMostRecent(this HtmlHelper html)
    {
        html.RenderAction("MostPopular", "Blog");
    }
}

and then in your view use your custom helper (after bringing the namespace in which the PartialHelper static class is defined into scope in the view):

@{Html.RenderMostRecent();}

You could also use the Action method instead of RenderAction:

public static class PartialHelper
{
    public static IHtmlString RenderMostRecent(this HtmlHelper html)
    {
        return html.Action("MostPopular", "Blog");
    }
}

which would allow you to invoke it like this in your view:

@Html.RenderMostRecent()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top