C# ASP.NET MVC中的应用程序助手

C# ASP.NET MVC中的应用程序助手,c#,asp.net-mvc,helpers,C#,Asp.net Mvc,Helpers,我正在寻找一种方法来创建一个应用程序助手,它允许您定义可以在所有控制器视图中调用的方法。在Rails中,您可以免费获得这些功能,但我如何在ASP.NET MVC和c#?中实现这一点?通常的方法是将扩展方法写入HtmlHelper——例如: public static string Script(this HtmlHelper html, string path) { var filePath = VirtualPathUtility.ToAbsolute(path); retur

我正在寻找一种方法来创建一个应用程序助手,它允许您定义可以在所有控制器视图中调用的方法。在Rails中,您可以免费获得这些功能,但我如何在ASP.NET MVC和c#?

中实现这一点?通常的方法是将扩展方法写入
HtmlHelper
——例如:

public static string Script(this HtmlHelper html, string path)
{
    var filePath = VirtualPathUtility.ToAbsolute(path);
    return "<script type=\"text/javascript\" src=\"" + filePath
        + "\"></script>";
}
公共静态字符串脚本(此HtmlHelper html,字符串路径)
{
var filePath=VirtualPathUtility.ToAbsolute(路径);
返回“”;
}

现在在视图中,您可以使用
Html.Script(“foo”)
etc(因为标准视图有一个名为
Html
HtmlHelper
成员)。您也可以在基本视图中编写方法,但扩展方法方法似乎是最常见的方法。

我建议在基本控制器类中添加一个扩展方法

public static class ControllerExtensions
{
    public static string Summin(this Controller c)
    {
        return string.Empty;
    }
}
您可以访问控制器中的帮助器功能:

  public class MyController : Controller
    {
        public ActionResult Index()
        {
            this.Summin();
            return View();
        }
    }

按照我的解释,它是从视图而不是控制器中想要的。。。不过变化不大。