Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Element not closed" error after upgrading from MVC3 to MVC4

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?

like image 591
Drew Noakes Avatar asked Oct 02 '12 16:10

Drew Noakes


2 Answers

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">
like image 55
Drew Noakes Avatar answered Nov 15 '22 07:11

Drew Noakes


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 }
like image 23
Dhrumil Bhankhar Avatar answered Nov 15 '22 07:11

Dhrumil Bhankhar