Tuesday, January 12, 2016

Razor Helper - ASP.NET MVC

There are two ways to implement this

Razor helper can be added directly to a view. 
For an instance lets go into the _Layouts.cshtml view and add the below Razor helper after the </html> tag

@helper Script(string scriptName) { 
    <script src="@Url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
    }

Now at the top of the page within the <head> tag you could reference the razor helper as:

@Script("jquery-1.4.4.js")
@Script("jquery-1.4.4.min.js")

- OR -

Rather than having the Razor helpers at the bottom of the view page, you could move it to a separate file inside app_code. For that we need to do the below changes

1. Add the app_code folder in the solution if not available
2. Inside the folder create a MVC View Page(Razor). The page I created in my example is Content.cshtml
3. Delete all mark-up available in the page and move the helper script into the page

So the below code goes to the newly created view. You need to have the using directive 

@using System.Web.Mvc;

@helper Script(string scriptName, UrlHelper url)
{
    <script src="@url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
}

4. In the view file (Eg: _Layout.cshtml)  refer the helper  as:

   @Content.Script("jquery-1.4.4.js", Url)
   @Content.Script("jquery-1.4.4.min.js", Url)





No comments:

Post a Comment