Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else statement in Razor is not functioning

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

 @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.Display("--");
                }
                else
                {
                    String.Format("{0:0.##}", item.Amount);
                }
            </td>
        </tr>

    }

However, no matter my model amount is null or having a value, the html rendered do not contain any value in the amount.

I wonder why this is happening. Any idea?

Thanks...

EDIT:

Decided to did it in controller:

   // Function to return shop list food item amount
    public string GetItemAmount(int fid)
    {
        string output = "";

        // Select the item based on shoplistfoodid
        var shopListFood = dbEntities.SHOPLISTFOODs.Single(s => s.ShopListFoodID == fid);

        if (shopListFood.Amount == null)
        {
            output = "--";
        }
        else
        {
            output = String.Format("{0:0.##}", shopListFood.Amount);
        }
        return output;
    }

and call at View like:

 <td class="shoptableamount">
                @Html.Action("GetItemAmount", "Shop", new { fid = item.ShopListFoodID })
            </td>
like image 808
shennyL Avatar asked Sep 10 '25 06:09

shennyL


1 Answers

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

like image 93
Gabriele Petrioli Avatar answered Sep 13 '25 10:09

Gabriele Petrioli