Using a Razor @functions in several webpages (.cshtml files)

让人想犯罪 __ 提交于 2019-11-26 18:26:41

问题


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;
    }
}

回答1:


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));

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




回答2:


You can define "global" helper functions in a Razor file in the AppCode directory as described here: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx. However, helpers only render page elements; they cannot return a value (or more correctly, the returned value is the HTML markup to be rendered).

If you need to return a value, your best bet is an extension method.




回答3:


Don't see why you couldn't have a static class with a static method and just include it at the top of every view and then use it



来源:https://stackoverflow.com/questions/17602507/using-a-razor-functions-in-several-webpages-cshtml-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!