"Item is not closed" error after upgrading from MVC3 to MVC4

Razor 2 (which ships with MVC4) does not seem to be fully compatible with Razor 1 (from MVC3).

Since the update, I found an error:

The td@Html.Raw (count) element has not been closed. All elements must either be self-closing or have an appropriate end tag.

The code that caused this:

< td@Html.Raw (count == null ? null : " class='has-item'")> 

What is the solution to this?

+6
source share
2 answers

The Razor parser was rewritten for MVC 4, presumably because :

The HTML5 specification clearly states that hidden HTML tags are supported, but Razor v1 did not have a strong enough parser to support this. Razor v2 now supports this with the elements listed in the W3C specification.

The simplest solution here is to add one 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 is resolved to null , the attribute is not specified in the element. So the output of this markup:

 <td> 

... or...

 <td class="has-item"> 
+14
source

The Razor MVC4 parser is different from MVC3. Razor v3 has advanced parser functions, and on the other hand, strict parsing is comparable to MVC3.

When converting MVC3 to MVC4, you may encounter a syntax error if you did not use razor syntaxes in the right way.

The solutions to some common razor code errors that are not allowed in Razor v2 are as follows:

-> Avoid using server blocks in views if there is no variable declaration section.

 Don't : @{if(check){body}} Recommended : @if(check){body} 

-> Avoid using @ when you are already in the server area.

 Don't : @if(@variable) Recommended : @if(variable) Don't : @{int a = @Model.Property } Recommended : @{int a = Model.Property } 
+1
source

Source: https://habr.com/ru/post/926776/


All Articles