0

I'm trying to upload multiple excel files.

However I am getting error messages as below: "Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object."

Below is the part of "Index.cshtml" where I upload files:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="postedFile1" id="file1" />
    <input type="file" name="postedFile2" id="file2" />
    <input type="submit" value="Upload" />
}

Below is a part of my "HomeController.cs". The foreach part is being highlighted so I assume that postedFile is not getting the uploaded files.

        [HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> postedFiles)
        {
            // Upload file on Server
            string path = Server.MapPath("~/Uploads/");
            string filePath = string.Empty;
            string extension = string.Empty;
            var ExcelDatas = new List<DataSet>();

            foreach (HttpPostedFileBase postedFile in postedFiles)
            {
                if (postedFile != null)
                {

How can I fix this?

jginso7
  • 77
  • 7
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ian Kemp Feb 22 '21 at 08:12

1 Answers1

1

When you want to send a list of items to the server, you must use the same name for the items. I changed the property of the inputs to name="postedFiles".

change Index.cshtml to below code

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="postedFiles" id="file1" />
    <input type="file" name="postedFiles" id="file2" />
    <input type="submit" value="Upload" />
}
Lucas Ethen
  • 2,716
  • 1
  • 4
  • 11
  • I changed the name but I'm still getting the same error. ```if (postedFiles == null) { return Content("None!"); }``` This gives me the "None!" page, so I'm still quite sure that ```postedFiles``` is still empty. – jginso7 Feb 22 '21 at 15:00
  • it's impossible . I tested the code. Full information was posted. – Lucas Ethen Feb 22 '21 at 15:20
  • 1
    I just changed the name to ```postedFile``` not ```postedFiles```. It works now Thanks! – jginso7 Feb 22 '21 at 15:27