我有一个可以工作的表单上传,但我想传递数据库的模型信息,当然可以使用不同的名称保存文件。
这是我的 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/