与模型MVC上传文件 - 第二个参数发布的文件为null [英] mvc upload file with model - second parameter posted file is null
本文介绍了与模型MVC上传文件 - 第二个参数发布的文件为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为null。但是这样做的时候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.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上传文件 - 第二个参数发布的文件为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文