0

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

4

1 回答 1

1

您可以将其编写为HtmlHelper类的扩展方法:

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

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

然后在您的视图中使用您的自定义助手(在将PartialHelper定义静态类的命名空间引入视图范围之后):

@{Html.RenderMostRecent();}

您也可以使用该Action方法代替RenderAction

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

这将允许您在视图中像这样调用它:

@Html.RenderMostRecent()
于 2013-08-21T16:12:50.087 回答