This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on

Sunday, March 20, 2011

jQuery IntelliSense with ASP.NET MVC and the Razor View Engine

The Razor view engine in ASP.NET MVC3 brings great improvements to the readability of code in the view.  Unfortunately, some of what I’d previously lamented in missed productivity improvements has stuck around.

If you are working with Razor’s reimplementation of Master Pages – Layouts – then you will likely run into the same kind of limitations with IntelliSense that existed in previous ASP.NET editors: you simply don’t get IntelliSense for jQuery on your views when you include the script reference in your _Layout.cshtml.

Enabling IntelliSense

The only way to get those digits moving at the speed of computer-type-it-for-me is to add the script references to your view.  Because we don’t want the script written to the page twice – once through the viewstart/layout and once through the view – we simply use our old if(false) trick (see part way down) to get IntelliSense back online.

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

Write the if block out and then drag and drop the files from your scripts folder in the Solution Explorer as an easy way to do this.  Once you’ve done this once, you can then put it in your Toolbox by highlighting the code and dragging it to the Toolbox window.  Here, I’m about to rename it to something more useful:


How This Could Be Fixed

To understand why it’s not working we have to look at what the IDE is aware of and what it does to figure out what styles/scripts are available in the editor.

When you’re on a view, Visual Studio doesn’t really know which layout will be used to render the view.  In some cases you may have many and you may be dynamically selecting it based on, for instance, the role of a logged in user.

However, we also know that the MVC Framework relies heavily on convention, and chances are that the default, most-used scenario with the ViewStart/_Layout.cshtml being used is likely the one that most folks will be dealing with.

So I would propose this: in the event that there is only one _Layout in the Views folder, assume that this is the one that will be used. Infer style sheet and script references from this file and enable IntelliSense based on the same.

1 comment:

  1. Great post, thanks.

    FYI, it appears the problem exists (at least for me) in all views which use src="@Url.Content("") - including _Layout. As a test, try opening _Layout and start typing <div class= <--you should get intellisense at this point. I suspect the problem is that VS ingores the string parameter for Url.content.

    The good news is that the @if (false) {} fixes this problem as well.