通过视图模型上传的文件为空

file uploading through view model coming as null

我有如下两个视图模型

public class hdr_doc_upload
{
    public string document_name { get; set; }
    public HttpPostedFileBase UpFile { get; set; }
}

public class list_doc
{
    public List<hdr_doc_upload> hdr_doc_upload { get; set; }
}

控制器

public ActionResult Create_Group()
{
    list_doc list = new list_doc();
    return View(list);
}

查看

@Html.TextBoxFor(model => model.hdr_doc_upload[0].document_name)
<input type="file" id="hdr_doc_upload[0].UpFile" name="hdr_doc_viewmodel[0].UpFile" />
@Html.TextBoxFor(model => model.hdr_doc_upload[1].document_name)
<input type="file" id="hdr_doc_upload[1].UpFile" name="hdr_doc_viewmodel[1].UpFile" />

屏幕下方给我

但是当我提交页面时,我们只得到文本框的值,文件被设为空。

您创建的手动 <input> 元素具有 name 与您的模型无关的属性。属性需要

name="hdr_doc_upload[0].UpFile" // not hdr_doc_viewmodel[0].UpFile

但是,您应该在 for 循环内使用强类型 TextBoxFor() 方法正确生成文件输入控件。

在您的控制器中,使用 hdr_doc_upload 的 2 个新实例填充您的模型,然后再将模型传递给视图

list_doc list = new list_doc()
{
    new list_doc(),
    new list_doc()
};
return View(list);

然后在视图中

for(int i = 0; i < Model.Count; i++)
{
    @Html.TextBoxFor(model => model.hdr_doc_upload[i].document_name)
    @Html.TextBoxFor(model => model.hdr_doc_upload[i].UpFile, new { type = "file" })
}