if else statement in Razor is not functioning

前端 未结 4 897
轻奢々
轻奢々 2021-02-05 05:01

I am using an if else in Razor view to check for null value like this:

 @foreach (var item in Model)
    {
        
                  


        
相关标签:
4条回答
  • 2021-02-05 05:06

    I think you want to display "-----" if amount is null.

    @foreach (var item in Model)
        {
            <tr id="@(item.ShopListID)">
                <td class="shoptablename">@Html.DisplayFor(modelItem => item.Name)
                </td>
                <td class="shoptableamount">
                    @if (item.Amount == null)
                    {
                        @Html.Raw("--")
                    }
                    else
                    {
                        String.Format("{0:0.##}", item.Amount);
                    }
                </td>
            </tr>
    
        }
    
    0 讨论(0)
  • 2021-02-05 05:14

    That's because you are using the Display() method incorrectly. The overload you are using is Display(HtmlHelper, String). If you are looking for "--" to be the text, you should use something like:

    @Html.Label("--");
    
    0 讨论(0)
  • 2021-02-05 05:25

    You have to use the @()

                @if (item.Amount == null)
                {
                    @("--");
                }
                else
                {
                    @String.Format("{0:0.##}", item.Amount)
                }
    

    As noted in the comments and other answers, the Html.Display is not for displaying strings, but for displaying data from the ViewData Dictionary or from a Model. Read http://msdn.microsoft.com/en-us/library/ee310174%28v=VS.98%29.aspx#Y0

    0 讨论(0)
  • 2021-02-05 05:33

    There are actually two other ways to display text from a code block in razor besides the suggested @(""), using a <text> tag and it's shorthand @:

        @{
            @("--")
            <text>--</text>
            @:--
        }
    

    The code above will display -- three times.

    0 讨论(0)
提交回复
热议问题