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.
I wasted so much time and it turns out that all I needed to do was to use the name attribute as well
<input type="file" name="somename">
the name attribute was missing in my new project.