通过使用具有
HttpPostedFileBase
属性绑定到视图,这样表单只需要一个post方法即可上传图像,然后将实体添加到数据库中。
这是表单标签:
@using (Html.BeginForm("Create", "Lessons", FormMethod.Post, new {enctype = "multipart/form-data" }))
以及绑定到视图模型属性的视图控件(默认情况下,如果名称匹配,则会发生这种情况,在我的情况下,属性为
Http发布的文件库
文件:
<input type="file" name="file" />
这比我在下面所走的道路要容易得多,我试图为一个视图有两个不同的后期操作(从我读到的所有内容来看,这应该是可能的,但我认为我的问题是试图在表单中有一个表单):
我的Lesson控制器有两个post方法,可以调用:
第一步是创建一个新课程:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Lesson lesson)//, WebImage Photo)
{
if (ModelState.IsValid && Request.Form["Create"]!=null)
//Request.Form check because the image file function is calling back to this handler
//Once that is sorted out the check can be removed and simply use ModelState.IsValid
{
db.Lessons.Add(lesson);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.DivID = new SelectList(db.Divisions, "ID", "DivName", lesson.DivID);
ViewBag.ProjectID = new SelectList(db.Projectinformations, "ID", "Code", lesson.ProjectID);
ViewBag.PeopleID = new SelectList(db.Peoples, "ID", "Firstname", lesson.PeopleID);
return View(lesson);
}
在页面上,这是一个表单(缩写),带有调用控制器的提交按钮。Create()操作:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
//. . . for each Lesson property there is a form group with @Html Label
//@Html.EditorFor, etc. and then at the bottom is this:
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" name="Create" class="btn btn-default" />
</div>
</div>
图像路径字段是主表单的一部分,我为它的文本框等留下了生成的代码。这是我试图插入调用不同控制器操作的图像上传的表单部分:
<div class="form-group">
<div class="col-md-10">
<form action="UploadImage" name="ImageFileForm" id="imageForm" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="OK" name="OK" />
</form>
</div>
@Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Image, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })
</div>
</div>
这是UploadImage的控制器操作
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImage(HttpPostedFileBase file)
{
string imagePath ="";
if (file != null)
{
var newFileName = Path.GetFileName(file.FileName);
imagePath = @"LessonsLearnedImages\" + newFileName;
file.SaveAs(@"~\" + imagePath);
}
ViewBag.DivID = new SelectList(db.Divisions, "ID", "DivName", lesson.DivID);
ViewBag.ProjectID = new SelectList(db.Projectinformations, "ID", "Code", lesson.ProjectID);
ViewBag.MOAPeopleID = new SelectList(db.MOApeoples, "ID", "Firstname", lesson.MOAPeopleID);
ViewBag.Image = imagePath;
return View();
}
然而,当我按下ImageUpload按钮时,会调用控制器Create(表单默认值)函数。我可能会使用控制器中的Create操作来执行Request.Form检查的所有操作,但在向其添加HttpPostedFileBase参数时,这对我来说失败了。