指数超出范围。必须是非负数且小于集合的大小

时间:2012-04-07 09:57:22

标签: file-upload validation webmatrix

在尝试验证页面上的表单数据时,出现以下错误:

  

System.ArgumentOutOfRangeException:索引超出范围。必须是非负数且小于集合的大小。
  参数名称: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];

1 个答案:

答案 0 :(得分: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