【问题标题】:Html.RenderAction as static methodHtml.RenderAction 作为静态方法
【发布时间】:2013-08-21 16:11:39
【问题描述】:

我最近开始使用 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()

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

如果有更简单的方法,欢迎提出想法!

谢谢

【问题讨论】:

    标签: c# asp.net-mvc-4 renderaction


    【解决方案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()
    

    【讨论】:

    • 太棒了!使这项工作唯一需要做的就是将第一个参数更改为“this HtmlHelper html”以使其成为扩展方法。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2011-05-29
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多