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

时间:2009-03-09 10:27:47

标签: c# asp.net-mvc helpers

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

2 个答案:

答案 0 :(得分:3)

通常的方法是将扩展方法写入HtmlHelper - 例如:

public static string Script(this HtmlHelper html, string path)
{
    var filePath = VirtualPathUtility.ToAbsolute(path);
    return "<script type=\"text/javascript\" src=\"" + filePath
        + "\"></script>";
}

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

答案 1 :(得分:0)

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

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