【问题标题】:How to insert upload file data and form data from view to database in MVC如何在MVC中将上传文件数据和表单数据从视图插入数据库
【发布时间】: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 作为第二个参数,但它不起作用。我需要修改路由配置还是其他地方?
  • 否 - 你是说 postedFilenull(它工作正常)?
  • Create函数只带一个参数,要么绑定表单控件,要么绑定postedFile。
  • 什么? - public ActionResult Create(grant grant, HttpPostedFileBase postedFile) - 但是您的编辑数据总是使用视图模型,并且该视图模型将仅包含您编辑的属性以及 HttpPostedFileBase 属性

标签: asp.net-mvc


【解决方案1】:

放第二个参数

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

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多