VisualStudio auto format does not format my razor code

I am using @:</div> to correctly display some bootstrap columns. This is my code where I use it:

 var i = 0; <div class="container-fluid"> <div class="row show-grid"> @foreach (var one in Model) { if (i % 3 == 0) { @:<div class="row show-grid"> } <div class="one-element col-md-4"> @one.Title </div> if ((i + 1) % 3 == 0) { @:</div> } i++; } </div> </div> 

It formats this (which works fine until I use the VisualStudio auto-formatting function):

 @:</div> 

:

 @: </div> 

And then the application no longer works.

How can this be fixed?

+8
c # asp.net-mvc razor
source share
3 answers

I fixed it using @Html.Raw() as follows:

 var i = 0; <div class="container-fluid"> <div class="row show-grid"> @foreach (var one in Model) { if (i % 3 == 0) { @Html.Raw("<div class=\"row show-grid\">") } <div class="one-element col-md-4"> @one.Title </div> if ((i + 1) % 3 == 0) { @Html.Raw("</div>") } i++; } </div> </div> 

I guess this is as good as it gets.

But if anyone knows a more elegant way to do this, please let me know.

+1
source share

Ok, now I realized that I was wrong with the <text> and this is why :

In Razor, tags must be properly nested. <text></div></text> there is no correct attachment.

The best way to solve your problem: @Alexei Levenkov:

 <div class="container-fluid"> <div class="row show-grid"> @foreach (var one in Model.Select((value, index) => new { value, index }).GroupBy(x => x.index / 3)) { <div class="row show-grid"> @foreach (var el in one.Select(x => x.value)) { <div class="one-element col-md-4"> @el.Title </div> } </div> } </div> </div> 

But according to this answer , your Html.Raw() approach is good enough.

0
source share

The problem seems to be that you open the <div> under the condition if (i % 3 == 0) , but you do not close the </div> in the same state if ((i + 1) % 3 == 0) .
This means that you may have an opening <div> that never closes or a closing </div> that never opens.
Perhaps you can try the following:

 var i = 0; <div class="container-fluid"> <div class="row show-grid"> @foreach (var one in Model) { <div class="one-element col-md-4"> @one.Title </div> if (i % 3 == 0) { <div class="clear"></div> } i++; } </div> </div> 

Maybe you have a problem! I updated your comment. update the comment by @Alexei Levenkov . I also look at the best way to do this. This solution is how I do it in my projects when I need 3 columns per row.

-2
source share

All Articles