Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refering jQuery in cshtml using HTML helper

I usually refer a jQuery using:

<script src='@(Url.Content("~/JavaScript/jquery.maskedinput-1.2.2.js"))' type="text/javascript"></script>

I refer the same Jquery in many Pages. Any change to the static content (name or version number) requires that all views are updated to absorb the change.In order to solve this I tried creating routes in Global.asax for Jquery file like below

routes.MapRoute("jquery.maskedinput.js", "Javascript/jquery.maskedinput-1.2.2.js");

and i tried to call it in cshtml using a Html Helper like below

 <script src='@Html.RouteLink("maskedinput","jquery.maskedinput.js") ' type="text/javascript"></script>

I know RouteLink returns a Anchor tag and so the Source is not rightly set for the Jquery to load.

Requirements:

  1. Is there any other Html helper which can return only the virtual path (or)
  2. I need to reference Jquery with a name not with a path. The path should be declared somewhere globally so that a single change in the global file can solve the purpose.

Help me, please.

like image 379
Vidiya Prasanth Pappannan Avatar asked Mar 11 '26 18:03

Vidiya Prasanth Pappannan


2 Answers

I use this method for my BundleCollection with System.Web.Optimization see my question, but this still works even with out it.

namespace PROJECT.Classes
{
    public class JSBundles
    {
        public static string Test = "/scripts/test.js";
    }

then use it like this:

<script src='@(JSBundles.Test)' type="text/javascript"></script>

which renders

<script src='/scripts/test.js' type="text/javascript"></script>

Note that this requires a reference in your view to PROJECT.Classes or wherever you put it. I've got that setup in my web.config in the views folder.

....
<add namespace="PROJECT.Classes" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
like image 89
Eonasdan Avatar answered Mar 17 '26 04:03

Eonasdan


You could use the popular and awesome RequireJS to inject jquery (and any other js dependancies) using javascript instead of serving them manually

http://requirejs.org/docs/jquery.html provides setup & usage instructions

like image 38
Dogoku Avatar answered Mar 17 '26 03:03

Dogoku