Reputation: 699
I don't know what I'm missing, but I need to upload a file using C# MVC 3. I followed instructions here in SO, but the file is always empty.
Here is my actual testing code:
HTML
@using (Html.BeginForm("Prc", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />
}
Controller
[HttpPost]
public ActionResult Prc(HttpPostedFile file)
{
if (file != null && file.ContentLength > 0)
{
var filename = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("~/Content/Images"), filename);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
When I run the web app, I attach a file, and click Submit. But when I reach the Controller
, the file
object is null
. Always null
. I tried an XML
file, a JPEG
file, and a GIF
file but none of them worked.
Should I configure something else besides just these codes?
Thanks
Upvotes: 0
Views: 2862
Reputation: 3841
One more thing might trip you up.
Using asp.net mvc 3 razor, I was just surprised to discover that the name of the HttpPostedFileBase variable passed to the controller method must match the id and name of the file input tag on the the view. Otherwise asp.net passes null for the HttpPostedFileBase variable.
For example, if your file input looks like this: < input type="file" name="filex" id="filex" />
And your controller method looks like this: public ActionResult Uploadfile(HttpPostedFileBase filey)
You'll get NULL for the "filey" variable. But rename "filey" to "filex" in your controller method and it posts the file successfully.
Upvotes: 2
Reputation: 139758
In MVC you need to use HttpPostedFileBase
instead of the HttpPostedFile
:
[HttpPost]
public ActionResult Prc(HttpPostedFileBase file)
{
//...
}
Upvotes: 2