Tuesday 19 February 2013

Brace yourself: Razor @Sections fail

Every now and then a bug is so hard to track down that when you do, you have to blag about it to let off some steam.


ASP.net MVC3 + Razor + Layouts + Sections can be a lovely combo - except when it isn't. Gere's the situation: you have a rogue bastard brace printing on your page and you figure that it's from some JavaScript syntax error or a Razor foreach fail but you are finding no errors. You could be the victim of a Razor bug.

Your _Layout has a Section like so:

@RenderSection("FooterScripts", required: false)

And your View contains code like so:

@section FooterScripts {
<script type="text/javascript">
function () {
    if (1 === 1) { // bla {
        console.log("bla");
    }
}
</script>
}


Everything is ok, right? Wrong. In the line with the comment, Razer completely assplodes and THAT is the line that is producing the extra brace on your view page. There are Many variations on this but all of the following produce a rogue brace in mvc3+razer+section (Yeah, it even fails on different rows).
  • if (1 === 1) { // bla {
  • if (1 === 1) { /* bla { */
  • if (1 === 1) { // bla { //AAAAAAA
  • if (1 === 1) { 
    // {
Be on the lookout for some nasty bugs. Solution: Use Razor comments and it'll work:

  • if (1 === 1) { @* bla { *@

No comments:

Post a Comment