I have an ASP.Net Core view and in it I'm trying to shrink the text shown, I could use:
@if (item.Details.Length < 100)
{
<span>@item.Details</span>
}
else
{
<span>@item.Details.Substring(0, 99) ...</span>
}
But then I thought I could use the conditional operator:
<span>@{item.Details.Length < 100 ? item.Details : item.Details.Substring(0, 99);}</span>
I'm guessing this doesn't work for the same reason this doesn't work:
@if (item.Details.Length < 100)
{
item.Details;
}
else
{
item.Details.Substring(0, 99);
}
i.e. the syntax needs to be broken into html
and cs
parts, but is there any syntax I can use to assign and display the variable in the one-liner using the conditional operator?
Please don't tell me that all the display logic should be done in the ViewModel. I know that might be the best option but that's not what I'm asking!
;
- what you've got isn't a valid statement but it is a valid expression. As ever, it would really help if you'd include the exact error message you're getting instead of making us guess.;
it tells me it's expected. When I add the;
it gives meOnly assignment, call ... expressions can be used as a statement.
{}
that's causing the problem. How about@(item.Details.Length < 100 ? item.Details : item.Details.Substring(0, 99))
?x
in-line then pop that between the<element>
tags - I didn't know this was possible until now()
instead of{}
- worked like a charm. I knew I'd done this before! The()
are evaluating the expression whereas the {} is more of a code-block?