在多个网页(.cshtml 文件)中使用 Razor @functions [英] Using a Razor @functions in several webpages (.cshtml files)

查看:22
本文介绍了在多个网页(.cshtml 文件)中使用 Razor @functions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the below function that I would like to be available to several .cshtml views in my asp.net web pages 2 application. How can I make this function available to any view in the application (as opposed to just one).

@functions {

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

推荐答案

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

Create a file called Functions.cshtml in App_Code and then paste the code you have into the file. Then you can call the DisplayButton method in any .cshtml file by prefixing it with the file name:

var myBool = Functions.DisplayButton(DateTime.Now, DateTime.Now.AddDays(30));

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

For more on working with functions and helpers in ASP.NET Web Pages, read this: http://www.mikesdotnetting.com/Article/173/The-Difference-Between-@Helpers-and-@Functions-In-WebMatrix

这篇关于在多个网页(.cshtml 文件)中使用 Razor @functions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆