1

I keep on getting null with HttpPosterFileBase when I try uploading a file:

I have this code in my view:

@using (Html.BeginForm("Import", "Control", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="fileUpload"/>
    <input type="submit" value="Import" id="btnImport" class="button" />
}

And this code with my controller:

[HttpPost]
public ActionResult Import()
{    
     HttpPostedFileBase file = Request.Files[fileUpload];            
     Other codes...
}

I also tried this in my controller:

[HttpPost]
public ActionResult Import(HttpPostedFileBase fileUpload)
{        
    Other codes...
}

After pressing the submit button the "file" got a value of null.

tereško
  • 58,060
  • 25
  • 98
  • 150
SyntaxError
  • 3,717
  • 6
  • 30
  • 31

4 Answers4

1

The default model binder binds by name for files. Your inputs name is fileUpload.. your parameter name is file. Making them the same will work.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
0

You're not doing your binding correctly, change this:

[HttpPost]
public ActionResult Import(HttpPostedFileBase file)
{        
    // other stuff
}

To:

[HttpPost]
public ActionResult Import(HttpPostedFileBase fileUpload)
{        
    // other stuff
}
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
0

Your names can't match because this code below works for me, unless you use some kind of jQuery or Ajax that's preventing this to work you should be good. It's the name of the file upload input and the HttpPostedFileBase name that must match.

@using (Html.BeginForm("import", "control", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="fileupload" />
    <input type="submit" value="Import" id="btnImport" class="button" />
}



[HttpPost]
public ActionResult Import(HttpPostedFileBase fileupload)
{
      return View();
}
Dejan.S
  • 18,571
  • 22
  • 69
  • 112
0

Thanks everyone for your answers. I believe all those answers are correct but I was able to fix the problem after I notice that I have nested forms with page. Found the solution after reading the answer here: MVC. HttpPostedFileBase is always null

Again, Thanks! Cheers! :)

Community
  • 1
  • 1
SyntaxError
  • 3,717
  • 6
  • 30
  • 31