I have a simple model with 1 string property which I render on a simple view.
the view looks like the following:
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { encType="multipart/form-data" }))
{
@Html.TextBoxFor(m => m.FirstName)
<br /><br />
<input type="file" name="fileUpload" /><br /><br />
<input type="submit" value="submit me" name="submitme" id="submitme" />
}
Controller is this:
[HttpPost]
public ActionResult UploadFile(UploadFileModel model, HttpPostedFileBase file)
{
// DO Stuff
return View(model);
}
Now, when I submit, the model DOES get populated but the second parameter being HttpPostedFileBase is null. However when doing Request.Files - it does seem to show there is a file in the Request being posted. How can I actually get the second parameter to bind?
For dealing with a single file input you can define a
HttpPostedFileBase
property within the ViewModel:And then implement it in the following way:
View:
@model SomeModel
Controller:
In case you need to deal with multiple files, you can either:
public HttpPostedFileBase SomeFile
property to something likepublic List<HttpPostedFileBase> SomeFiles
and then span multiple@Html.TextBoxFor(m => m.SomeFile, new { type = "file" })
controls to have them all within that list.In case you need additional info check out this blog post that I wrote on the topic.
Why not add the uploaded files to your model like this:
Then change your view to this:
Then your files will be posted back as follows:
Alternatively, (if acceptable) remove the [Required] validation annotation for your file from your model and check for the file in your Controller action, and add an error if not found:
Change your name
file
tofileUpload
andenctype
it's work