I have a Post controller on a model with some string fields and an image. Exact identical code works on MVC4 but in MVC 5 the Request.Files.Count is always 0
My model has byte[] for image rather than HttpPostedFileBase
My View:
@using (Html.BeginForm("Create", "HotelManager", FormMethod.Post, new { enctype = "multipart/form-data", data_ajax = "false" }))
{
@Html.AntiForgeryToken()
@Html.TextBoxFor(model => model.Title, new { @class = "form-control" })
@Html.TextAreaFor(model => model.Description, new { @class = "form-control", @rows = "7" })
<input type="file" class="form-control filestyle">
<input type="submit" value="Submit" class="btn btn-block" />
}
I have tried omitting data_ajax = "false" but no use.
My Post Controller is as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Title,Description,Image")] Hotel hotel)
{
if (ModelState.IsValid)
{
// deal with the uploaded file
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
// Code to process image, resize, etc goes here
}
}
// Other code to add the hotel to db goes here
}
In the debugger I see that the Request.Files.Count is always zero, I don't know why? I have copied over both the view and controller code from another MVC4 project where it works fine.
Key Value
Request POST /HotelManager/Create HTTP/1.1
Accept text/html, application/xhtml+xml, */*
Referer http://localhost:4976/HotelManager/Create
Accept-Language en-US,en;q=0.5
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; ASU2JS; rv:11.0) like Gecko
Content-Type multipart/form-data; boundary=---------------------------7de207070a24
Accept-Encoding gzip, deflate
Host localhost:4976
Content-Length 946
DNT 1
And in the IE Developer window I see that the form body is empty.
One of the reasons why Request.Files.Count becomes 0 is when you try to upload a file larger than the maxRequestLength specified on Web.config file. Make sure to check this value if you are having an issue with Request.Files.Count.
UPDATE: This answer might not be directly related to OP's issue, but since google lists this post top for Request.Files.Count=0 issue, posted the answer which worked for me.
I wasted so much time and it turns out that all I needed to do was to use the name attribute as well
the name attribute was missing in my new project.
To add on You need to change the post method.
Need to add:
Here is complete form tag
Those lines are essential; without them, you will not be able to save an input of type file. I sat for 6 hours trying to figure that out.
You need to change the post method
Need to add:
Here is complete form tag
See how can you post multiple files