带有模型的 mvc 上传文件 - 第二个参数发布的文件为空 [英] mvc upload file with model - second parameter posted file is null
问题描述
我有一个带有 1 个字符串属性的简单模型,我将其呈现在一个简单的视图上.
I have a simple model with 1 string property which I render on a simple 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" />
}
控制器是这样的:
[HttpPost]
public ActionResult UploadFile(UploadFileModel model, HttpPostedFileBase file)
{
// DO Stuff
return View(model);
}
现在,当我提交时,模型确实被填充,但 HttpPostedFileBase 的第二个参数为空.但是,在执行 Request.Files 时 - 它似乎确实显示正在发布的请求中有一个文件.我怎样才能真正获得要绑定的第二个参数?
Now, when I submit, the model DOES get populated but the second parameter being HttpPostedFileBase is null. However when doing Request.Files - it does seem to show there is a file in the Request being posted. How can I actually get the second parameter to bind?
推荐答案
为什么不像这样将上传的文件添加到您的模型中:
Why not add the uploaded files to your model like this:
public class UploadFileModel
{
public UploadFileModel()
{
Files = new List<HttpPostedFileBase>();
}
public List<HttpPostedFileBase> Files { get; set; }
public string FirstName { get; set; }
// Rest of model details
}
然后将您的视图更改为:
Then change your view to this:
@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" />
}
然后您的文件将按如下方式回发:
Then your files will be posted back as follows:
public ActionResult UploadFile(UploadFileModel model)
{
var file = model.Files[0];
return View(model);
}
这篇关于带有模型的 mvc 上传文件 - 第二个参数发布的文件为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!