1

I have this code below and if I put the String.Format inside a if statement nothing gets rendered in the view. FYI - if I remove the semi colons from the if statements then there is a red line indicating error. This doesn't happen in the non if statement

@{
   TimeSpan span = (ybEvent.UtcDate.AddDays(-1) - DateTime.UtcNow);
}
// this works
@String.Format("{0}d {1}hr {2}min", span.Days, span.Hours, span.Minutes)

// this doesn't work - does not render anything in view
@if (span.Days > 0)
  {
     String.Format("{0}d {1}hr {2}min", span.Days, span.Hours, span.Minutes);
   } else
   {
    if (span.Hours > 0)
    {
        String.Format("{0}hr {1}min", span.Hours, span.Minutes);
    } else
    {
      String.Format("{0}min", span.Minutes);
    }
 }

1 Answer 1

4

Try putting it inside a tag:

@if (span.Days > 0)
{
    <text>@String.Format("{0}d {1}hr {2}min", span.Days, span.Hours, span.Minutes)</text>
}
else
{
    if (span.Hours > 0)
    {
        <text>@String.Format("{0}hr {1}min", span.Hours, span.Minutes)</text>
    }
    else
    {
        <text>@String.Format("{0}min", span.Minutes)</text>
    }
}

The <text> tag has a special meaning in Razor, it will not be sent to the output. Of course you could have used any other HTML tag instead such as <span> or <div> to wrap the output

Sign up to request clarification or add additional context in comments.

4 Comments

ya that worked, but what's better, a text tag or a span tag??
That will depend on whether you want this tag to be placed inside the resulting markup or not. Use <text> if you don't want to wrap the text in the resulting markup in any tag. Use <span> or <div> if you want to apply some additional styling to the text in the resulting markup.
not sure what the difference is? I tried with both and they both show the rendered string on the screen!
Look at the generated HTML. You will not see the <text> tag in it because it is an invalid tag. It will not be rendered.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.