2013-08-21 45 views
0

我最近开始玩MVC4,现在我正在接受部分视图。Html.RenderAction作为静态方法

我现在有一个控制器,像这样:

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() 

这样我就可以在任何时候更改控制器/操作,而且我无需在任何地方更新即可调用该局部视图。

如果有一个更简单的方法来做到这一点,打开想法!

感谢

回答

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方法代替o ˚FRenderAction

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

这将允许你调用它像这样在您的看法:

@Html.RenderMostRecent() 
+0

真棒!使这项工作唯一需要的是将第一个参数改为'this HtmlHelper html',以使其成为扩展方法。非常感谢! – seanxe

+0

你是对的。我忘了那个。答案已更新。 –