Weiyang Sim
Weiyang Sim

Reputation: 21

CSV file upload error

When I want to try the file upload in ASP.Net MVC, I am receiving the following error.

file error

A first chance exception of type 'System.NullReferenceException' occurred in administratorPortal.dll

file error

The thread '' (0x21e4) has exited with code 0 (0x0). A first chance exception of type 'System.NullReferenceException' occurred in administratorPortal.dll

in my view

<form action="../../Controllers/patientAppointmentController.cs" method=post>
<input id="model" type="file" name="fileUpload" data-val="true" data-val-required="File is required" />
<input class="btn btn-primary" type="submit" value="Import" />
</form>  

in my controller

public ActionResult CSVUpload(HttpPostedFileBase fileUpload)
    {
        try
        {
            Debug.Write(fileUpload.ContentLength);

            if (fileUpload.ContentLength < 0 || fileUpload == null)
            {
                Debug.Write("unable to detectFile");
            }
        }
        catch
        {
            Debug.Write("file error");
        }
        return View();
    }

there is some problem, i cant even get the file passed to the controller. i had tried many different method found on the internet, but none of them work for me.

Upvotes: 2

Views: 272

Answers (2)

Kami
Kami

Reputation: 19407

The form appears to be pointing to the incorrect location

<form action="/patientAppointment/CSVUpload" method="post" enctype="multipart/form-data">
  <input id="model" type="file" name="fileUpload" data-val="true" data-val-required="File is required" />
  <input class="btn btn-primary" type="submit" value="Import" />
</form>  

as @Fals has pointed out, you also need to decorate the method with the HttpPost attribute to indicate it receives a form.

[HttpPost]
public ActionResult CSVUpload(HttpPostedFileBase fileUpload)
{
    try
    {
        Debug.Write(fileUpload.ContentLength);

        if (fileUpload.ContentLength < 0 || fileUpload == null)
        {
            Debug.Write("unable to detectFile");
        }
    }
    catch
    {
        Debug.Write("file error");
    }
    return View();
}

Upvotes: 4

Irwin
Irwin

Reputation: 12819

Shouldn't your form's action point to the address of the resource and not the .cs file?

Upvotes: 1

Related Questions