Reputation: 1909
Been trying to implement a file uploader with multiple files and I keep getting an invalid ModelState
. Here's my code (just the essentials)
ViewModel:
public IEnumerable<HttpPostedFileBase> files { get; set; }
view.cshtml:
@model ITManagement.ViewModels.AssetViewModel
@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Asset</h4>
<hr />
.
. The rest of the form is located here
.
.
<div class="form-group">
@Html.LabelFor(viewModel => viewModel.objectModel.documentInfo.documents.fileContent, htmlAttributes: new {@class = "control-label col-md-2" } )
<div class="col-md-2">
<input class="single-line" [email protected](viewModel => viewModel.files)
[email protected](viewModel => viewModel.files)
type="file" multiple="multiple" />
</div>
</div>
controller:
[Route("create", Name = AssetsControllerRoute.Create)]
public ActionResult create()
{
AssetViewModel evm = new AssetViewModel();
return View(evm);
}
// POST: Assets/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Route("create")]
public ActionResult create(AssetViewModel asset)
{
if (ModelState.IsValid)
{
erepo.add(asset.objectModel);
return RedirectToAction("Index");
}
return View(asset);
}
I've already encountered this question and then subsequently this error and answer, but I'm still missing something. The files
variable is empty when I upload a file and submit the form. I do see using Request.Files
in my searching, but what's the difference between trying to bind to an IEnumerable<HttpPostedFileBase>
and using Request.Files
?
Here's the reason for the invalid ModelState:
"The parameter conversion from type 'System.String' to type 'System.Web.HttpPostedFileBase' failed because no type converter can convert between these types."
Upvotes: 3
Views: 5261
Reputation: 1909
The one piece of code I had wrong was this
@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
This should instead be
@using (Html.BeginForm("create", "assets", FormMethod.Post, new { enctype = "multipart/form-data" }))
"create" represents the controller action, and "assets" represents the controller name. I gave it these 3 parameters and everything was fine.
Upvotes: 10