0

i have a form where you enter information about the picture and upload it, the upload code in the html form is :

 @FileUpload.GetHtml(
                initialNumberOfFiles: 1,
                allowMoreFilesToBeAdded: false,
                includeFormTag: false,
                uploadText: "Upload"); 

and in the c# code in the same page i got :

                            var fileName = "";
                            var fileSavePath = "";
                            var uploadedFile = Request.Files[0];
                            fileName = Path.GetFileName(uploadedFile.FileName);
                            fileSavePath = Server.MapPath("~/Images/inscriptions/" +
                            fileName);
                            uploadedFile.SaveAs(fileSavePath);

for some reason i get the error "index out of range" on the line :

var uploadedFile = Request.Files[0];

i want the user to click browse choose the file and fill the other Text boxes and click save to upload the picture and fill the info in the database(which is handled)

1 Answer 1

1

I figured out your problem may be solved with one of these solutions:

Solution 1: Change includeFormTag: false to includeFormTag: true.

@FileUpload.GetHtml(
            initialNumberOfFiles: 1,
            allowMoreFilesToBeAdded: false,
            includeFormTag: true,
            uploadText: "Upload");

This solution apply if FileUpload helper placed outside any form tag.

Solution 2: Use Html.BeginForm with attribute enctype="multipart/form-data" that wraps FileUpload helper.

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @FileUpload.GetHtml(
            initialNumberOfFiles: 1,
            allowMoreFilesToBeAdded: false,
            includeFormTag: false,
            uploadText: "Upload");
}

This solution apply if you don't want to create new form tag by FileUpload helper and use existing form instead.

NB: IndexOutOfRangeException on Request.Files[0] originated from form submission request which omitted file part contained in <input type="file" />, hence you need to include enctype="multipart/form-data" attribute (see explanation here).

Related problems:

How to use @FileUpload.GetHtml inside Html.BeginForm and sumbit FilesList

Trying to work with Request.Files in WebMatrix

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks i just added the enctype part to my existing form and it worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.