我正在寻找一种方法来创建一个应用程序帮助程序,它允许您定义可以在所有控制器视图中调用的方法。在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(&quot; foo&quot;); 等(因为标准视图有一个名为 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();
        }
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top