asp.net-mvc - MVC 3 文件上传和模型绑定(bind)

标签 asp.net-mvc asp.net-mvc-3 razor

我有一个可以工作的表单上传,但我想传递数据库的模型信息,当然可以使用不同的名称保存文件。

这是我的 Razor View :

@model CertispecWeb.Models.Container

@{
  ViewBag.Title = "AddDocuments";
}

<h2>AddDocuments</h2>

@Model.ContainerNo

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, 
            new { enctype = "multipart/form-data" }))
{
    <input type='file' name='file' id='file' />
    <input type="submit" value="submit" />
}

这是我的 Controller :

[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
     if (file.ContentLength > 0)
     {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"),
                       containers.ContainerNo);
        file.SaveAs(path);
     }

     return RedirectToAction("Index");
}

模型信息不会传递到 Controller 。我已了解到我可能需要更新模型,我该怎么做?

最佳答案

您的表单不包含除文件之外的任何输入标记,因此在 Controller 操作中您不能期望获得除上传的文件(这就是发送到服务器的所有内容)之外的任何内容。实现此目的的一种方法是包含一个包含模型 ID 的隐藏标签,该标签允许您从要发布到的 Controller 操作内的数据存储中检索它(如果用户不应该修改模型但只需附加一个文件):

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(x => x.Id)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

然后在你的 Controller 操作中:

[HttpPost]
public ActionResult Uploadfile(int id, HttpPostedFileBase file)
{
    Containers containers = Repository.GetContainers(id);
    ...
}

另一方面,如果您希望允许用户修改此模型,那么您需要为要发送到服务器的模型的每个字段包含正确的输入字段:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(x => x.Prop1)
    @Html.TextBoxFor(x => x.Prop2)
    @Html.TextBoxFor(x => x.Prop3)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

然后您将让默认模型绑定(bind)器根据请求重建此模型:

[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
    ...
}

关于asp.net-mvc - MVC 3 文件上传和模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4784225/

相关文章:

c# - 尝试连接到 Microsoft Graph 时出现 "Failed to acquire token silently"错误

asp.net-mvc - 为什么 Visual Studio 代码格式不能正常用于 Razor 标记?

asp.net-mvc-3 - MetadataType 缺少程序集引用

c# - 使用 Entity Framework 的重叠任命

asp.net - 为什么使用 Azure 云服务项目而不是带有 Azure SDK 的 ASP.NET 项目?

c# - TinyMCE.MVC.Jquery 不会显示?

asp.net-mvc-3 - Razor 内联if语句不起作用?

c# - 使用 GetProperty 语法在 Umbraco 7 中获取媒体 url

c# - 从代码访问 View 模型所需的错误消息数据注释属性 - MVC、Razor

JQuery 在 Controller 上调用 Action(但之后不重定向)