如何在MVC中将上传文件数据和表单数据从视图插入数据库

时间:2018-02-07 23:28:11

标签: asp.net-mvc

我有一个create view来将视图数据插入数据库。该视图具有上载文件文本框以及其他文本框。如何绑定表单数据并将上传的文件以字节为单位插入表中?

@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);
}

控制器无法同时插入表单数据和上传文件数据到数据库。我该怎么做?感谢。

1 个答案:

答案 0 :(得分:0)

放第二个参数

Create([Bind(Include = "id,Princial_name,p_campus,filepath,filedata")] grant grant, HttpPostedFileBase postedFile)