2013-04-16 31 views
0

在此條件語句中,我嘗試了最後一部分,以嘗試執行代碼段(如果我的表單集合爲空)。FormCollection檢查是否爲空

if ((myDT == null) || (myCollection.GetKey(0).ToString() == "heatSearch") || (myCollection == null)) 
{ 
    //some code here 
} 

每次我運行代碼和表單集合爲空,此時這種情況下應該是真實的,我的應用程序崩潰,我收到此錯誤:索引超出範圍。必須是非負數且小於集合的大小。

更多信息...此檢查正在由AJAX帖子調用的ActionResult中執行。該帖子是什麼失敗,並返回此處顯示的此行的錯誤:<b> Source File: </b> c:\Users\D\Documents\Visual Studio 2012\Projects\TheMProject(1)\TheMProject\Models\HomeModel.cs<b> &nbsp;&nbsp; Line: </b> 936

行936是與if一起。

+0

代碼中的哪一行會給出錯誤?這不是'如果',是嗎? –

+1

'AllKeys.ToString()'沒有多大意義。測試它:'System.String []' –

+0

@Conrad Clark是的,它發生在包含if的行上。 – HendPro12

回答

2

修復:

if ((myDT == null) || (myCollection == null) || (myCollection.GetKey(0).ToString() == "heatSearch")) 
{ 
    //some code here 
} 

你測試之前調用myCollection.GetKey(0)如果myCollection爲null。

+0

:(仍然沒有成功) – HendPro12

+0

好吧,用(myCollection.Count == 0)代替(myCollection == null)可以正常工作,謝謝你指出GetKey檢查不能得到第一個結果。 – HendPro12

0

你試過......

public ActionResult MyAction(FormCollection f) 
{ 
    if (f.Count == 0) 
     { 
      Debug.WriteLine("Hello"); 
     } 

     return View(); 
} 
+0

我剛剛嘗試過,仍然收到相同的錯誤。 – HendPro12