【发布时间】:2018-02-08 13:30:49
【问题描述】:
我有一个创建函数来将视图数据插入数据库。该视图有一个上传文件文本框以及其他文本框。如何绑定表单数据并将上传的文件以字节为单位插入到表中?
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Princial_name)
@Html.EditorFor(model => model.Princial_name)
@Html.ValidationMessageFor(model => model.Princial_name)
@Html.LabelFor(model => model.p_campus)
@Html.EditorFor(model => model.p_campus)
@Html.ValidationMessageFor(model => model.p_campus)
@Html.LabelFor(model => model.filepath)
<input type="file" name="postedFile" />
<input type="submit" value="Submit" class="btn btn-default" />
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,Princial_name,p_campus,filepath,filedata")] grant grant)
{
HttpPostedFileBase postedFile;
byte[] bytes;
using (BinaryReader br = new BinaryReader(postedFile.InputStream))
{
bytes = br.ReadBytes(postedFile.ContentLength);
}
if (ModelState.IsValid)
{
grant.id = Guid.NewGuid();
db.Entry(grant).State = EntityState.Modified;
//add filepath
db.Entry(grant).Property("filepath").CurrentValue = Path.GetFileName(postedFile.FileName);
db.Entry(grant).Property("filedata").CurrentValue = bytes;
db.grant.Add(grant);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(grant);
}
控制器不能同时插入表单数据和上传文件数据到数据库。我该怎么做?谢谢。
【问题讨论】:
-
您没有从文件输入中读取值(您所做的一切都在初始化
HttpPostedFileBase的新实例)。在您的 POST 方法签名中添加一个HttpPostedFileBase postedFile参数,使其绑定。 -
我在 Create() 函数中添加了 HttpPostedFileBase postedFile 作为第二个参数,但它不起作用。我需要修改路由配置还是其他地方?
-
否 - 你是说
postedFile是null(它工作正常)? -
Create函数只带一个参数,要么绑定表单控件,要么绑定postedFile。
-
什么? -
public ActionResult Create(grant grant, HttpPostedFileBase postedFile)- 但是您的编辑数据总是使用视图模型,并且该视图模型将仅包含您编辑的属性以及HttpPostedFileBase属性
标签: asp.net-mvc