Asp.Net MVC throw error when I add the folder 'App_Code'

509 Views Asked by At

Today, I found a very nice feature giving me the ability to add cshtml helper. To be able to do that, I must put cshtml file in a folder named 'App_Code' and then adding into a code that looks like that:

@using System.Security.Policy

@helper jQuery(){
   if (System.Diagnostics.Debugger.IsAttached)
   {
        <script src="@Url.Content("~/Scripts/JQuery/jquery-1.7.2.js")" type="text/javascript"></script>
   }
   else
   {
        <script src="@Url.Content("~/Scripts/JQuery/jquery-1.7.2.min.js")" type="text/javascript"></script>
   }
}

The problem is immediatly after adding this folder with just one file, when I try to access page in browser, I receive a server error.

"NetworkError: 500 Internal Server Error - http://localhost/[Port]...

I already have code into other folders of my project.

Must I have to move all my code into the 'App_Code' folder or is there any trick to keep my existing structure but with this new 'App_Code' folder?

Thank you.

1

There are 1 best solutions below

4
On BEST ANSWER

You can't use helpers within the helper so they are not as helpful as you might have initially thought :-)

Things like Html and Url don't exist within those helper functions. So if you need to use them, you will have to pass them as parameters:

@using System.Web.Mvc
@using System.Security.Policy

@helper jQuery(UrlHelper urlHelper)
{
   if (System.Diagnostics.Debugger.IsAttached)
   {
        <script src="@urlHelper.Content("~/Scripts/JQuery/jquery-1.7.2.js")" type="text/javascript"></script>
   }
   else
   {
        <script src="@urlHelper.Content("~/Scripts/JQuery/jquery-1.7.2.min.js")" type="text/javascript"></script>
   }
}

and when calling pass the instance of the current UrlHelper to it:

@Foo.jQuery(Url)