Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc razor extra space

Razor inserts extra space between text blocks. I want to render a list this way: "1, 2, 3" but get "1 , 2 , 3".

@for (int i = 1; i < 3; i++) {   <text>@i</text>   if (i != 2)   {     <text>, </text>   } } 

Are there any ways to remove this extra space?

like image 510
SiberianGuy Avatar asked Nov 26 '10 04:11

SiberianGuy


People also ask

Does ASP.NET MVC use razor?

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. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML.

Can you mix MVC and Razor pages?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder.

What is @model in razor page?

It is a self-contained class that represents the data and behaviour of a specific "view" or page. The view model pattern is used extensively in MVC application development, where it mainly represents data, but typically little behaviour. In Razor Pages, the PageModel is also the view model.


2 Answers

Since this still a problem with the <text> tag in MVC 3 RTM + Tools Update and it can be a real headache to deal with, an alternative to eddiegroves' approach of removing whitespace from the code formatting is to avoid the use of the <text> tag altogether.

First, here is a rewrite of the original code that reproduces the problem and actually prints "1 , 2 , 3":

    @for (int i = 1; i <= 3; i++) {       @i       if (i < 3) {         <text>, </text>       }     } 

Here are four alternatives that print "1, 2, 3" instead of "1 , 2 , 3", but preserve code formatting by using @something instead of <text>.

Solution #1: Using @("")

@for (int i = 1; i <= 3; i++) {     @i     if (i < 3) {         @(", ")     } } 

Solution #2: Using @var

@for (int i = 1; i <= 3; i++) {     var s = i < 3 ? ", " : null;     @i @s } 

Solution #3: Using @(expression)

@for (int i = 1; i <= 3; i++) {     @i @(i < 3 ? ", " : null) } 

Solution #4: Using @helpers

@helper Item(int index) {     @index }  @helper Separator(int index, int count) {     if (index < count) {         @(", ")     } }  @for (int i = 1; i <= 3; i++) {     @Item(i) @Separator(i, 3) } 

That last one is obviously overkill for the example, but might be a useful pattern for more complicated items and separators.

like image 94
Chris Thoman Avatar answered Sep 18 '22 07:09

Chris Thoman


You could use @Html.Raw. The code is more readable and the output doesn't have extra whitespace

@for (int i = 1; i < 3; i++) {   @Html.Raw(i)   if (i != 2)   {     @Html.Raw(", ")   } } 
like image 38
Adam Tegen Avatar answered Sep 20 '22 07:09

Adam Tegen