Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor View Engine: Complex looping and HTML

I have lots of complex HTML reports in my current project where there we perform lots of conditional rendering of TRs and TDs with rowspans and colspans.

It could sometimes look like this (this is extremely simplified):

<tr> @foreach (var ourItem in ourList) {    if (ourItem != ourList.First()) {       <tr>                    }    <td></td>    </tr> } 

However, Razor claims: "The foreach loop is missing a closing "}" character". (within Visual Studio)

I've tried to wrap the <tr> in <text></text> which makes the closing } problem go away only to find this when run: "Encountered end tag "tr" with no matching start tag. Are your start/end tags properly balanced".

How would I do this kind of conditional rendering while convincing Razor not to bother about the HTML at all, cause the HTML is balanced when all the looping is done. Or at least that was the case when the ASP.NET View Engine was used.

like image 456
Mikael Östberg Avatar asked Jan 24 '11 12:01

Mikael Östberg


People also ask

What is Cshtml vs HTML?

Cshtml is basically razor view extension and any view renders in html finally. You need to use Razor in your application as it supports server side code but raw html does not.

What is razor view HTML?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.

What is Razor in MVC why it is used?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML.


1 Answers

Visual Studio Intellisense and syntax highlighting is not one of the best but in this case it warns you that if the condition is not satisfied, you might get invalid markup and you shouldn't blame it for this.

The important thing is that your project runs fine but you might consider externalizing this logic into HTML helpers because if what you are saying is true that this is a simplified version of what you have in the views I don't even want to imagine how your actual code looks.

IMHO having so much conditional logic in a view is an abuse. You definitely should consider using HTML helpers or controls such as MVCContrib Grid.


UPDATE:

You may try the following hack:

<tr> @foreach (var ourItem in ourList) {    if (ourItem != ourList.First()) {       @:<tr>                    }    @:<td></td>    @:</tr> } 
like image 121
Darin Dimitrov Avatar answered Sep 20 '22 14:09

Darin Dimitrov