2011-12-18 78 views
21

我使用的是如果別人在Razor視圖來檢查空值是這樣的:如果在剃刀else語句不工作

@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> 

    } 

但是,不管我的模型量爲空或有一個值時,所呈現的html不包含任何值。

我想知道爲什麼會發生這種情況。任何想法?

謝謝...

編輯:

決定要這麼做是控制器:

// 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; 
    } 

,並在視圖中調用,如:

<td class="shoptableamount"> 
       @Html.Action("GetItemAmount", "Shop", new { fid = item.ShopListFoodID }) 
      </td> 
+0

您將不得不向我們展示模型本身的外觀,特別是Model.Amount字段。也許嘗試@if(string.IsNullOrEmpty(item.Amount))而不是? – 2011-12-18 02:42:31

+0

嗨,感謝您的幫助,但金額是一個小數,如果我按照這裏說的一個,它沒有工作。無論如何,請參閱我的編輯,因爲我決定在控制器中做到這一點,謝謝:) – shennyL 2011-12-18 02:56:51

+0

如果其他組合確實無法在剃刀中使用。 – Anderson 2014-12-10 15:47:41

回答

58

您必須使用@()

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

正如評論和其他答案中所述,Html.Display不用於顯示字符串,而是用於顯示ViewData字典或Model中的數據。閱讀http://msdn.microsoft.com/en-us/library/ee310174%28v=VS.98%29.aspx#Y0

+0

如果我在剃鬚刀中這樣做,你的答案是有效的:@if(item.Amount == null) { @ Html.Display(「 - 」) } 但我不能得到空檢查工程,所以我決定而不是在控制器中。謝謝! – shennyL 2011-12-18 02:55:42

+1

@shennyL檢查我的答案和dotnetstep的答案。我不認爲Display()方法正在做你認爲正在做的事情。 – 2011-12-18 02:56:45

+0

@shennyL,正如@Shark指出的那樣,除了缺少實際輸出內容的'@'外,'Html.Display'沒有做你認爲的那樣.. – 2011-12-18 03:07:21

6

我想你想要顯示「-----」如果金額爲空。

@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> 

    } 
1

這是因爲您錯誤地使用了Display()方法。您使用的超負荷是Display(HtmlHelper, String)。如果您正在尋找「 - 」是文本,你應該使用類似:

@Html.Label("--"); 
1

其實有另外兩種方法在剃鬚刀顯示來自一個代碼塊文本除了建議@(「」) ,使用<文本>標籤和它的簡寫@:

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

上面的代碼會顯示 - 三次。