我有一个带有 1 个字符串属性的简单模型,我在一个简单 View 上进行渲染。
View 如下所示:
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { encType="multipart/form-data" }))
{
@Html.TextBoxFor(m => m.FirstName)
<br /><br />
<input type="file" name="fileUpload" /><br /><br />
<input type="submit" value="submit me" name="submitme" id="submitme" />
}
Controller 是这样的:
[HttpPost]
public ActionResult UploadFile(UploadFileModel model, HttpPostedFileBase file)
{
// DO Stuff
return View(model);
}
现在,当我提交时,模型确实得到填充,但第二个参数 HttpPostedFileBase 为空。但是,在执行 Request.Files 时 - 它似乎确实显示正在发布的请求中有一个文件。 我怎样才能真正让第二个参数绑定(bind)?
最佳答案
为什么不像这样将上传的文件添加到您的模型中:
public class UploadFileModel
{
public UploadFileModel()
{
Files = new List<HttpPostedFileBase>();
}
public List<HttpPostedFileBase> Files { get; set; }
public string FirstName { get; set; }
// Rest of model details
}
然后将您的 View 更改为:
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { encType="multipart/form-data" }))
{
@Html.TextBoxFor(m => m.FirstName)
<br /><br />
@Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })<br /><br />
<input type="submit" value="submit me" name="submitme" id="submitme" />
}
然后您的文件将按如下方式回传:
public ActionResult UploadFile(UploadFileModel model)
{
var file = model.Files[0];
return View(model);
}
关于c# - 带模型的 mvc 上传文件 - 第二个参数发布的文件为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21677038/