I have a piece of MVC 2.0 html code is like below, I want replace it with MVC 3.0 Razor code, but I can not make it work using one line code like MVC 2.0.
<legend> Please add review for product :<%: Model.Product.ProductName.Length > 25 ? (string)Model.Product.ProductName.Substring(0, 25) + "..." : (string)Model.Product.ProductName %> <i style="color:Red">( <%: (string)Model.Product.Category.CategoryName %> )</i></legend>
The only way I can make it work is like below, but it looks not neat. I don’t like it, anyone can give me one line code which is worked in MVC 3.0 Razor will be great appreciate!!!
<legend> Please add review for product :
<b>
@{
if(Model.Review.Product.ProductName.Length > 25)
{
@Model.Review.Product.ProductName.Substring(0, 25); @:...
}
else
{
@Model.Review.Product.ProductName;
}
}
</b>
<i style="color:Red">( @Model.Review.Product.Category.CategoryName )</i> </legend>
The ternary operator (
x > y ? x : y) is usable in Razor. You just have to wrap it in brackets, so you can clean it up a lot by doing this (I’ve created a variable for product name for clarity’s sake):However, since what you’re doing is a fairly common task, you might want to think about creating an HTML helper method for the trimming:
Then you can just use:
@Html.Truncate(Model.Review.Product.ProductName, 25)in your view, which is much cleaner.You could also define an extension method on
string:which would allow you to just do this:
@Model.Review.Product.ProductName.Truncate(25).