2012-04-07 64 views
0

的大小非負少而試圖驗證我的網頁上表單數據,我得到以下錯誤:索引超出範圍。必須大於集合

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.

我對這個頁面的代碼是:

@{ 
var db= Database.Open("Games"); 
var sqlQ = "SELECT * FROM Games"; 
var data = db.Query(sqlQ); 
Page.Title = "Add Game"; 
} 
@{ 
    var fileerrorMessage = ""; 
    var NameerrorMessage = ""; 
    var Gamefile = ""; 
    var GameName = ""; 
    var fileData = Request.Files[0]; 
    var fileName = Path.GetFileName(fileData.FileName); 
    var fileSavePath = Server.MapPath("~/upload/" + fileName); 
    GameName=Request["formName"]; 
    Gamefile=fileName; 
    if (IsPost) { 
    var isValid = true; 
     if (Gamefile.IsEmpty()){ 
      fileerrorMessage = "Please upload a file."; 
      isValid = false; 
     } 

     else if (GameName.IsEmpty()){ 
      NameerrorMessage = "Please give the game a name."; 
      isValid = false; 
     } 

     if (isValid){ 

     fileData.SaveAs(fileSavePath); 
     var SQLINSERT = "INSERT INTO Games (Name, file_path) " + "VALUES (@0, @1)"; 
     db.Execute(SQLINSERT, GameName, Gamefile); 
     Response.Redirect("default.cshtml"); 
     } 

     else 
     { 
      <p class="message error">Please correct the errors and resubmit the form.</P> 
     } 

    } 
} 
<form action="" method="post" enctype="multipart/form-data"> 

    <input type="file" name="file" id="file" /> 
    @if(!fileerrorMessage.IsEmpty()) { 
     <label for="file" class="validation-error"> 
      @fileerrorMessage 
     </label> 
    } 
    <p><input type="text" name="formName" value="@GameName" /> 
    @if(!NameerrorMessage.IsEmpty()) { 
     <label for="file" class="validation-error"> 
      @NameerrorMessage 
     </label> 
    } 

    <input type="submit" value="Add Game" /> 
</form> 

錯誤顯然是與線12,這意味着應該有一些錯誤:var fileData = Request.Files[0];

+0

那麼,你認爲發生在Request.Files是一個空數組?你試圖訪問第一個元素? – Konerak 2012-04-07 10:01:35

+0

那麼我該如何讓它非空? – mhcodner 2012-04-07 10:43:22

回答

1

如果試圖通過索引時,有沒有上傳的文件引用Request.Files,你會得到這個錯誤。您的代碼在頁面首次加載時運行,因此用戶沒有機會上傳文件,這意味着Request.Files必須爲空。

移動if(IsPost)你的聲明fileData和檢查Request.Files的計數上述企圖在它引用任何事情之前:

if(IsPost){ 
    if(Request.Files.Count > 0){ 
     var fileData = Request.Files[0]; 
     var fileName = Path.GetFileName(fileData.FileName); 
     var fileSavePath = Server.MapPath("~/upload/" + fileName); 
     //etc 
+0

是的,謝謝,但我設法解決它自己除外爲什麼我需要檢查request.files的長度? – mhcodner 2012-04-11 11:33:45

+0

對不起 - 應該是計數,而不是長度。 – 2012-04-12 04:55:02

相關問題