Enabling jQuery IntelliSense in an MVC project with Visual Studio 2010


Heads up!

The blog has moved!
The new URL to bookmark is http://blog.valeriogheri.com/


today I’d like to share with you a quick trick to enable IntelliSense to help writing jQuery code in the View.
If we are using the out of the box convention of MVC 3, our layout code will be placed in the Views/Shared/_layout.cshtml folder, and inside it we can put all of our scripts and stylesheets global references.

Then, when we write jQuery code in our own View, we will notice that we have no IntelliSense support helping us, contrary to our expectations.
The problem lies in the way Visual Studio works: IntelliSense engine will not be able to access the references we made into _layout because the engine doesn’t really know which layout will be used to render the View until the code is running (just imagine a scenario where we may dynamically choose a layout based on user profile to understand why Visual Studio works this way).

The solution

The first solution I came up with was to add again the vsdoc script reference (jquery-X.Y.Z-vsdoc.js) to the View and I had IntelliSense again.

Enabling Intellisense

Habemus IntelliSense!

The downside of this is double references that will produce double requests when browsing the site, and this is bad!

So I googled and I found a pretty nice trick to enable Intellisense and to avoid downsides(link):

@if (false)
<script src="../../Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script>

Surrounding the script reference by an if (false) statement, the reference will never be posted to the browser because the statement will always be false, but we will still have our Intellisense to help us!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s