2015-09-23 28 views
1

在索引視圖中我想檢查對象的參數是否爲空。 我已經做了下面的代碼。檢查剃鬚刀視圖中的對象參數是否爲空 - 索引?

<td>    
    @if (String.IsNullOrEmpty(item.Account.Name) == false) 
    { 
     @Html.ActionLink(item.Account.Name, "../Accounts/Details", new { id = item.Account.AccountID })     
    } 
    else 
    { 
     @Html.DisplayFor(modelItem => item.Account.Name) 
    } 
</td> 

而且我得到這個錯誤:

{"Object reference not set to an instance of an object."}

所以我應該怎麼檢查,如果在空參數?


1-ActionLink如果對象爲空但DisplayFor不會生成錯誤。

2 - 這是在索引視圖中的foreach循環。

+2

因爲'Account'是'null'(你需要先檢查一下) –

+0

你綁定了視圖嗎? –

+0

@StephenMuecke非常感謝你。 –

回答

4

由於@StephenMuecke的問題得到解決。以下是代碼變更:

@if (item.Account != null && String.IsNullOrEmpty(item.Account.Name) == false) 

Account應該先檢查。

0

首先你需要檢查item.Account,因爲它是空在某些情況下:

@if (item.Account != null) 
     { 
      if (!String.IsNullOrEmpty(item.Account.Name)) 
      { 
       @Html.ActionLink(item.Account.Name, "../Accounts/Details", new { id = item.Account.AccountID }) 
      } 
      else 
      { 
       @Html.DisplayFor(modelItem => item.Account.Name) 
      } 
     } 
+0

使用上面使用的代碼是錯誤的嗎? –

+0

您在if條件中使用item.Account.Name,但有可能您的item.Account爲null ...在這種情況下,它將拋出空引用異常。 –

+0

我的意思是我給我的文章的答案。 @Ankit –

相關問題