繁体   English   中英

HTML.RenderAction作为静态方法

[英]Html.RenderAction as static method

我最近开始使用MVC4,现在可以看部分视图。

我目前有一个像这样的控制器:

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

然后,使用以下命令行从我的任何视图中调用它:

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

是否可以做这样的事情:

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

因此,在我的代码中,我需要调用的是:

@PartialHelper.RenderMostRecent()

这样,我可以随时更改控制器/动作,而不必在调用该局部视图的所有地方进行更新。

如果有更简单的方法可以做到这一点,请公开讨论!

谢谢

您可以将其编写为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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM