简体   繁体   中英

string.Format not working in C# razor when inside if statement

I am using string.Format in a razor view to format items coming from my viewModel.

It is working fine when I use it like this:

<td>
   <b>@string.Format("{0:c}", item.TotalCreditPaid)</b>
</td>

But, when I try to use it within an if statement it is not displaying anything in the view:

      <td>
          <b>@if (item.AverageTimeToPay != null)
          {
            string.Format("{0} Days", item.AverageTimeToPay);
          }
          </b>
     </td>

I stepped through it and the if is being hit, the item.AverageTimeToPay has a value of 12, but it is not displaying anything.

Any idea why this is happening? Thanks!

You are missing the @ and parenthesis, change it to this instead.

  <td>
      @if (item.AverageTimeToPay != null)
      {
        <b>@(string.Format("{0} Days", item.AverageTimeToPay))</b>
      }
 </td>

The code is running, but it's not emitting anything to the page.

This will automatically emit to the page:

@string.Format("{0:c}", item.TotalCreditPaid)

because of how Razor syntax works. Basically the output of the line of code is emitted to the page. However, this is just plain code:

string.Format("{0} Days", item.AverageTimeToPay);

By itself it doesn't do anything, something needs to be done with its output. In your second example, the output of the if block is emitted to the page, but if blocks don't output anything. (The clue here is that semi-colon. It's subtle, but it's kind of an indicator that this is just a server-side line of code and not a Razor output statement.)

All you need to do is tell it to output to the page:

<td>
    @if (item.AverageTimeToPay != null)
    {
        <b>@string.Format("{0} Days", item.AverageTimeToPay)</b>
    }
</td>

The issue is that you aren't breaking out of the code block.

Try this instead:

  <td>
      @if (item.AverageTimeToPay != null)
      {
        <b>@string.Format("{0} Days", item.AverageTimeToPay)</b>
      }
 </td>

or

  <td>
      <b>@if (item.AverageTimeToPay != null)
      {
        @:@string.Format("{0} Days", item.AverageTimeToPay);
      }
      </b>
 </td>

You need to print the string to the page so try:

<td>
    <b>@if (item.AverageTimeToPay != null)
    {
        @string.Format("{0} Days", item.AverageTimeToPay);
    }
    </b>
</td>

You are not rendering your output to Html as string, You can do it in two ways

1)

 <b>
  @if (item.AverageTimeToPay != null)
  {
    @:@string.Format("{0} Days", item.AverageTimeToPay);
  }
  </b>

2)

  @if (item.AverageTimeToPay != null)
  {
    <b>@string.Format("{0} Days", item.AverageTimeToPay)</b>
  }

Check this fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM