After upgrading an ASP.NET MVC 3 project to ASP.NET MVC 4, my page failed to load with the following error message:
HttpParseException: Unexpected "this" keyword after "@" character.
Here is the failing code block. The exception occurs on line 5:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<head> | |
@using (profiler.Step("<head> rendering")) | |
{ | |
<title>@ViewBag.Title - MVC MiniProfiler Demo</title> | |
@this.TimeScript("Our CSS", | |
@<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />) | |
} | |
</head> |
This seems to be a bug in Razor V2 as mentioned here: http://aspnetwebstack.codeplex.com/workitem/458. The ASP.NET team decided not to fix this, so you have to use a workaround.
By adding some extra ‘()’ the error goes away:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<head> | |
@using (profiler.Step("<head> rendering")) | |
{ | |
<title>@ViewBag.Title - MVC MiniProfiler Demo</title> | |
(@this.TimeScript("Our CSS", | |
@<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />)) | |
} | |
</head> |