Razor 2 (which ships with MVC4) doesn't seem to be fully backwards compatible with Razor 1 (from MVC3).
Since upgrading, I found an error:
The "[email protected](count" element was not closed. All elements must be either self-closing or have a matching end tag.
The code that caused this was:
<[email protected](count == null ? null : " class='has-item'")>
What is the solution to this?
The Razor parser was re-written for MVC 4, presumably because:
The HTML5-specs clearly states that unclosed HTML-tags are supported, but Razor v1 didn't have an advanced enough parser to support this. Razor v2 now supports this with the elements listed in W3C's spec.
The simplest solution here is to add a single space before the @
symbol:
<td @Html.Raw(count == null ? null : " class='has-item'")>
However, conditional attributes in Razor with MVC 4 have a more elegant syntax.
<td class="@(count == null ? null : "has-item")">
When an attribute value resolves to null
, the attribute is omitted from the element. So the output of this markup is either:
<td>
...or...
<td class="has-item">
The Razor parser of MVC4 is different from MVC3. Razor v3 is having advanced parser features and on the other hand strict parsing compare to MVC3.
You may run into syntax error in view while converting MVC3 to MVC4 if you have not used razor syntaxes in correct manner.
Solution of some common razor code mistakes that are not allowed in Razor v2 are :
--> Avoid using server blocks in views unless there is variable declaration section.
Don’t : @{if(check){body}}
Recommended : @if(check){body}
--> Avoid using @ when you are already in server scope.
Don’t : @if(@variable)
Recommended : @if(variable)
Don't : @{int a = @Model.Property }
Recommended : @{int a = Model.Property }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With