0

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!

6
  • 1
    I would expect it to work if you just remove the ; - 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.
    – Jon Skeet
    Aug 24, 2020 at 8:51
  • Hi @JonSkeet it doesn't compile if I exclude the ; it tells me it's expected. When I add the ; it gives me Only assignment, call ... expressions can be used as a statement.
    – jamheadart
    Aug 24, 2020 at 8:54
  • 1
    Ah, it may be the use of {} that's causing the problem. How about @(item.Details.Length < 100 ? item.Details : item.Details.Substring(0, 99))?
    – Jon Skeet
    Aug 24, 2020 at 8:55
  • I just tried that I can actually declare a string x in-line then pop that between the <element> tags - I didn't know this was possible until now
    – jamheadart
    Aug 24, 2020 at 8:55
  • Ah, that's it! Using () 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?
    – jamheadart
    Aug 24, 2020 at 8:56

1 Answer 1

2

Currently, you're trying to use a conditional ?: expression as a statement - but it's not a statement expression. However, it is a valid expression in itself. So you need to:

  • Remove ; which is only valid after a statement
  • Change the {} (used for a block body) to () (used to tell Razor how much text is the expression)
<span>@(item.Details.Length < 100 ? item.Details : item.Details.Substring(0, 99))</span>

Note that in C# 8, you can use the range operator for more brevity:

<span>@(item.Details.Length < 100 ? item.Details : item.Details[..99])</span>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.