大家好,我正在尝试创建一个应用程序,该应用程序允许用户将多个图像上传到博客文章中,出于某种原因,当我使用它时,多个图像上传有效:
<input id="ImagePath" title="Upload a product image" multiple="multiple" type="file" name="files" />
但当我使用像这样的 Html 帮助程序时不会
@Html.TextBoxFor(model => model.ImagePath, new { type = "file", multiple = "multiple", name = "files" })
我得到的错误是一个空引用异常,但这些不一样吗?
它出现在这一行
foreach (var file in files)
视图
@model Crud.Models.PostModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@*@Html.LabelFor(model => model.ImagePath)
@Html.TextBoxFor(model => model.ImagePath, new { type = "file", multiple = "multiple", name = "files" })
@Html.ValidationMessageFor(model => model.ImagePath)*@
@Html.LabelFor(model => model.ImagePath)
<input id="ImagePath" title="Upload a product image" multiple="multiple" type="file" name="files" />
</div>
<div class="editor-field">
@Html.LabelFor(model => model.Heading)
@Html.TextBoxFor(model => model.Heading)
@Html.ValidationMessageFor(model => model.Heading)
</div>
<div>
@Html.LabelFor(model => model.PostBody)
@Html.TextBoxFor(model => model.PostBody)
@Html.ValidationMessageFor(model => model.PostBody)
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
控制器
public ViewResult Create()
{
return View("Create", new PostModel());
}
[HttpPost]
public ActionResult Create(PostModel Post, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
foreach (var file in files)
{
PostModel post = new PostModel();
if (file.ContentLength > 0)
{
string displayName = file.FileName;
string fileExtension = Path.GetExtension(displayName);
string fileName = string.Format("{0}.{1}", Guid.NewGuid(), fileExtension);
string path = Path.Combine(Server.MapPath("~/Img/"), fileName);
file.SaveAs(path);
post.ImageDisplayName = displayName;
post.ImagePath = fileName;
post.PostBody = Post.PostBody;
post.Heading = Post.Heading;
}
repository.Save(post);
}
}
return RedirectToAction("display");
}
因为这行代码
@Html.TextBoxFor(model => model.ImagePath, n
ew { type = "file", multiple = "multiple", name = "files" })
将生成这样的 HTML 标记
<input id="ImagePath" multiple="multiple" name="ImagePath" type="file" value="">
请注意,输入元素的名称仍然是"图像路径"?因为 HTML 帮助程序方法在生成元素名称属性值时使用属性名称。
如果要覆盖它,请使用大写属性名称。
这应该有效
@Html.TextBoxFor(model => model.ImagePath,
new { type = "file", multiple = "multiple", NAME = "files" })