Egydeveloper
Egydeveloper

Reputation: 195

error "Index was out of range" in razor application

I had this error when use upload file with razor page :

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

the error occurred here

var uploadedFile = Request.Files[0];

Controller:

[HttpPost]
public ActionResult Create(Category category)
{
    if (ModelState.IsValid)
    {
        var fileSavePath = "";
        var fileName = "";
        var uploadedFile = Request.Files[0];
        fileName = Path.GetFileName(uploadedFile.FileName);
        fileSavePath = Server.MapPath("../../Uploads/" + fileName);

        uploadedFile.SaveAs(fileSavePath);


        db.Categories.Add(category);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(category);
}

View:

@using (Html.BeginForm("Create", "Category", FormMethod.Post, 
                  new { enctype = "multipart/form-data" })) 
{
   <div class="editor-label">
        @Html.LabelFor(model => model.Path)
   </div>
   <div class="editor-field create-Bt3">
       @FileUpload.GetHtml(
          initialNumberOfFiles: 1,
          allowMoreFilesToBeAdded: false,
          includeFormTag: false,
          uploadText: "Upload")
   </div>
}

Upvotes: 2

Views: 2626

Answers (1)

Jan
Jan

Reputation: 16032

The error means, that the Request.Files collection does not contain any item.

You can check with the Count property for the number of files uploaded:

if (Request.Files.Count > 0) {
    var uploadedFile = Request.Files[0];
}

Check with fiddler what the browser is sending - maybe its an issue with the FileHelper

Upvotes: 2

Related Questions