While trying to validate form data on my page i get the following error:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.
my code for this page is:
@{
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>
The error is apparently with line 12. which means there should be something wrong with: var fileData = Request.Files[0];
If you try to reference Request.Files by index when there are no files uploaded, you will get this error. Your code runs when the page first loads, so the user has had no chance to upload a file, which means Request.Files is bound to be empty.
Move
if(IsPost)up above your declaration forfileDataand check the count of Request.Files before attempting to reference anything in it: