在几个网页中使用Razor @functions(.cshtml文件)

Rob*_*ert 17 asp.net razor asp.net-webpages

我有以下功能,我希望在我的asp.net网页2应用程序中可用于几个.cshtml视图.如何使该功能可用于应用程序中的任何视图(而不仅仅是一个).

@functions {

    public bool DisplayButton(String startDate, String endDate)
    {
        return Convert.ToDateTime(startDate) < DateTime.Now && Convert.ToDateTime(endDate) > DateTime.Now;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*ind 23

在App_Code中创建一个名为Functions.cshtml的文件,然后将您拥有的代码粘贴到文件中.然后,您可以在任何.cshtml文件中调用DisplayButton方法,方法是在其前面添加文件名:

var myBool = Functions.DisplayButton(DateTime.Now, DateTime.Now.AddDays(30));
Run Code Online (Sandbox Code Playgroud)

有关在ASP.NET网页中使用函数和帮助程序的更多信息,请阅读:http://www.mikesdotnetting.com/Article/173/The-Difference-Between-@Helpers-and-@Functions-In-WebMatrix