I recently started building my views in order to improve the quality and maintainability of my code after I switched to test-driven development too.
This helped a lot, and the compiler identified a few flaws in my views in terms of variables that had been renamed, or other things like that.
Now however, I am seeing some false positives when I build my solution. Here’s an example of some code that worked just fine before at runtime, but now won’t compile:
<script type="text/javascript">
var url = null;
@{
Html.Raw("url = 'doesnt work';");
}
url = "@Url.Action("DoesNotWorkEither")";
</script>
Remember that this actually runs when I execute it on the server without building the views first!
Errors received
-
Invalid character at the code
@{ -
Expected ‘;’ at the code
url = "@Url.Action("DoesNotWorkEither")";
How can I solve these errors?
Update 1
It should be noted that ignoring this error is not an option for me. You see, it can’t even build (because I enabled building of views). This means that it will fail to build on my build server too, where I have gated check-ins (which do no allow the checkin to be submitted before it has been built and tests have been run).
Update 2
As was explained to me in a comment to an answer, this is apparently just a Visual Studio parser error which can be ignored. The build server will in fact build the views too and tell you if there’s a concrete error in the view, but will ignore the false positives.
Those errors come from Visual Studio’s Javascript parser, which doesn’t know about Razor.
They have nothing to do with the build system.
You can safely ignore them.
You can hide the Razor code from the Javascript parser using comments and string literals, like this: (untested)
A better workaround would be to create extension methods that emit
<script>tags with the data you need, then don’t call Razor at all in<script>.