【发布时间】:2016-04-18 06:57:19
【问题描述】:
我正在尝试将我的图像上传到一个文件夹中,并且我正在尝试将图像路径放入我的数据库中。但我无法在 asp.net mvc 中获取我的输入文件。 我该如何解决这个问题以及如何在我的 Controller 中调用输入文件?
创建.cshtml
@model SecundaireSchool.Models.tblLeraren
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm(new { enctype= "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>tblLeraren</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.naam, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.naam, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.naam, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.emailadres, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.emailadres, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.emailadres, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.foto, "test" , htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.foto, "test" , new { type = "file", @class = "input-file", @name = "file" })
</div>
</div>
<!-- <div class="form-group">
@@Html.LabelFor(model => model.foto, htmlAttributes: new { @@class = "control-label col-md-2" })
<div class="col-md-10">
@@Html.EditorFor(model => model.foto, new { htmlAttributes = new { @@class = "form-control" } })
@@Html.ValidationMessageFor(model => model.foto, "", 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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
教师控制器
所以我成功地将图像路径插入到我的数据库中。但它不会将它添加到我的图像文件夹中。我做错了什么?
[HttpPost]
public ActionResult Create(tblLeraren teacher, HttpPostedFileBase file = null)
{
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
teacher.foto = path;
}
db.tblLerarens.Add(teacher);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(teacher);
}
【问题讨论】:
-
您没有带有
name="file"的文件输入(但您确实有带有name="foto"的文件输入-检查您生成的html!)您不能使用new { @name="file" } (fortunately). Create a separate input for the file upload -更改name属性 提交时会绑定到你的参数。
标签: asp.net asp.net-mvc