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?
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>
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With