[英]Html.RenderAction as static method
I've recently started playing with MVC4, and i'm now on to partial views. 我最近开始使用MVC4,现在可以看部分视图。
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 谢谢
You could write it as an extension method to the HtmlHelper
class: 您可以将其编写为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");
}
}
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): 然后在您的视图中使用自定义帮助器(在将PartialHelper
静态类定义在其中的名称空间带入视图的作用域之后):
@{Html.RenderMostRecent();}
You could also use the Action
method instead of RenderAction
: 您也可以使用Action
方法代替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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.