JavaScript Intellisense In Razor Views


Monday 15 Aug 2011 at 21:00
Development  |  c# asp.net intellisense extensions razor javascript

There’s an issue with getting JavaScript IntelliSense to display in a Razor view of an ASP.NET MVC project.

Turns out that despite having the JavaScript file corrected referenced within your _Layout.cshtml (or some other “global” location) like so:

<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
    @RenderSection("HeadContent", required: true)
</head>

The Visual Studio IDE won’t recognise or parse the:

<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>

line when you’re working inside other views within your project.

There’s a hacky workaround for this, though.  You have to reference the JavaScript file from within the view that you’re currently working in.  Although this seems counter-intuitive, and you certainly don’t want a doubly-referenced script as part of your actual solution code, you can place this “dummy” reference in a conditional block of code that will never be reached when your solution is running:

@* Stupid hack to get jQuery intellisense to work in the VS2010 IDE! *@
@if (false)
{
   <script src="../../Scripts/jquery-1.6.2-vsdoc.js" type="text/javascript"></script>
}

The if (false) conditional ensures that, when this code is running, the script reference will never be output to the page as the conditional will never evaluate to false (it’ll always evaluate to true).  Despite this, when you’re working in the Visual Studio IDE, the script reference will be parsed and the relevant JavaScript file included (in this case a vsdoc.js file containing the IntelliSense information for jQuery 1.6.2).  This is because the IDE doesn’t care that this script reference code is effectively unreachable, and will happily parse the entire code block anyway!