[英]Application helper in ASP.NET MVC
我正在尋找一種制作應用程序助手的方法,它允許您定義可以在所有控制器視圖中調用的方法。 在 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>";
}
現在在視圖中您可以使用Html.Script("foo");
等(因為標准視圖有一個名為Html
的HtmlHelper
成員)。 您也可以在基本視圖中編寫方法,但擴展方法方法似乎是最常見的。
我建議向基礎 controller class 添加擴展方法。
public static class ControllerExtensions
{
public static string Summin(this Controller c)
{
return string.Empty;
}
}
您可以在 controller 中訪問幫助程序 function:
public class MyController : Controller
{
public ActionResult Index()
{
this.Summin();
return View();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.