我尝试在我的视图中编写以下两行来上传文件。
@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
@using (Html.BeginForm("Create", "Attachments", FormMethod.Post, new { enctype = "multipart/form-data" }))
POST
操作符上的Create
操作的代码行Attachments
,两条线都显示我在Create
内设置的断点。但是,只有第二行正确上传附件。第一行的附件设置为null
。
为什么第一行不上传文件,即使它似乎也在POST
Create
上执行了Attachments
?
查看:
@using (Html.BeginForm(new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Attachment</h4>
<div class="form-group">
@Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.File, htmlAttributes: new { @class = "form-control", type = "file", name = "file"})
@Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "AttachmentID,AttachmentName")] Attachment attachment, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
db.Attachments.Add(attachment);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(attachment);
}
答案 0 :(得分:2)
要上传文件,<form>
元素需要enctype = "multipart/form-data"
属性。
您首次尝试使用this overload添加路由值,并假设GET方法是Create()
AttachmentsController
方法,您正在生成
<form action="/Attachments/Create?enctype=multipart/form-data" method="post">
并且没有enctype
属性,因此HttpPostedFileBase file
参数为null
。
第二次尝试使用this overload,其中第四个参数是htmlAttributes
并生成
<form action="/Attachments/Create" method="post" enctype="multipart/form-data">