47

I have a helper function that turns minutes into hours/mins. I currently have it in my layout.cshtml but each page cannot see the function. Where should I put the helper function such that every page can see it?

@helper DisplayElapsedTime(int timeInMins){
    String timeStr = "";
    if (timeInMins >= 60) {
        int hours = timeInMins/60;
        timeInMins -= hours * 60;
        timeStr = hours + "h ";
    }
    if (timeInMins > 0){
        timeStr += timeInMins + "m";
    }
    @timeStr;
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Chris
  • 26,744
  • 48
  • 193
  • 345

1 Answers1

45

You should put it into the App_Code folder. There is an awesome article for you to read ASP.NET MVC Helpers

petro.sidlovskyy
  • 5,075
  • 1
  • 25
  • 29
  • 2
    You may create it manually. It will work as expected. Just put it into the root of your MVC application and name App_Code. – petro.sidlovskyy Sep 04 '12 at 14:26
  • I had been reading that page only a few minutes ago, must have missed this section. Thanks! – Chris Sep 04 '12 at 14:28
  • 1
    This doesn't appear to work anymore. Create a new MVC5 project, add an App_Code folder, create a @helper library cshtml file, and it does not do whatever voodoo that it was previously doing. I wonder if they abandoned it? – Andrew Hoffman Aug 04 '14 at 17:05
  • 3
    @AndrewHoffman it still works, just tested it in a mvc5 project. Pay attention to filename. I have to reference it like: @.() – Jowen Aug 14 '14 at 13:51
  • 2
    People might be in the same situation like me, where this does not work. Do be aware of that you cannot mix programming languages in the App_Code folder! So if there is a cs file there you cannot add a cshtml file.Ref https://msdn.microsoft.com/en-us/library/t990ks23.aspx – oligofren Mar 22 '16 at 02:37
  • I think it still works ok in MVC 5. I've got cs files in my app_code folder, and as long as I specify the filename of the file in app_code containing the helpers, its fine, e.g. @MyFile.MyHelper() – Philip Johnson May 22 '17 at 08:16