我正在寻找一种制作应用程序助手的方法,它允许您定义可以在所有控制器视图中调用的方法。在 Rails 中,您可以免费获得它,但我如何在 ASP.NET MVC 中使用 c# 完成此操作?
Tom Maeckelberghe
问问题
687 次
2 回答
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");
etc(因为标准视图有一个HtmlHelper
名为 的成员Html
)。您也可以在基本视图中编写方法,但扩展方法方法似乎是最常见的。
于 2009-03-09T11:18:36.290 回答
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();
}
}
于 2009-03-09T11:22:26.950 回答