一直试图用多个文件实现文件上传器,我一直无效ModelState.这是我的代码(只是必需品)
视图模型:
public IEnumerable<HttpPostedFileBase> files { get; set; }
Run Code Online (Sandbox Code Playgroud)
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" id=@Html.IdFor(viewModel => viewModel.files)
name=@Html.NameFor(viewModel => viewModel.files)
type="file" multiple="multiple" />
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
控制器:
[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);
}
Run Code Online (Sandbox Code Playgroud)
我已经遇到过这个问题,然后又出现了这个错误和答案,但我仍然遗漏了一些东西.files当我上传文件并提交表单时,变量为空.我确实看到Request.Files在我的搜索中使用,但尝试绑定IEnumerable<HttpPostedFileBase>和使用之间的区别是什么Request.Files?
以下是无效ModelState的原因:
"从'System.String'类型到'System.Web.HttpPostedFileBase'类型的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换."
我错了的一段代码就是这个
@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
Run Code Online (Sandbox Code Playgroud)
这应该是
@using (Html.BeginForm("create", "assets", FormMethod.Post, new { enctype = "multipart/form-data" }))
Run Code Online (Sandbox Code Playgroud)
"create"表示控制器操作,"assets"表示控制器名称.我给了它这3个参数,一切都很好.
| 归档时间: |
|
| 查看次数: |
2964 次 |
| 最近记录: |