Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC and Razor to display integer or blank when 0

If I have an integer value that I want to display on a page, I can do that a number of ways:

<span>@Html.DisplayFor(modelItem => item.UserId)</span>
<span>@item.UserId</span>

But what is the best way to convert that to displaying the value IF UserId != 0. But if UserId == 0, display an empty string. Is there a way to do it right in Razor syntax or do I need to head to code?

like image 540
slolife Avatar asked Sep 25 '12 22:09

slolife


2 Answers

Create an extension method for int:

public static class IntExtensions
{
    public static string EmptyIfZero(this int value)
    {
        if(value == 0)
            return string.Empty;

        return value.ToString();
    }
}

... and then in your Razor view, do:

<span>@item.UserId.EmptyIfZero()</span>
like image 100
Sebastian Leth Avatar answered Oct 02 '22 13:10

Sebastian Leth


<span>@((item.UserID == 0) ? "" : @item.UserID.ToString())</span>

OR

<span>@if(item.UserID == 0) { <span></span> }
   else { @Html.DisplayFor(m => item.UserID); }
</span>

I think you could do this with one if condition

<span>@if(item.UserID != 0) { @Html.DisplayFor(m => item.UserID); } //the browser would render empty string by itself

To render content without putting the redundant (as you said) <span>, use the @: - MVC3 Razor: Displaying html within code blocks and @: for displaying content

<span>
   @if(item.UserID == 0) {  } //this is redundant too
   else { @Html.DisplayFor(m => item.UserID); 
   }
</span>

Note that I have moved the } to next line. ASP.Net MVC did not accept it

<span>
   @if(item.UserID == 0) { @:Some content with no html tag wrapper 
   }
   else { @Html.DisplayFor(m => item.UserID); 
   }
</span>
like image 33
codingbiz Avatar answered Oct 02 '22 14:10

codingbiz