从 MVC 视图中发布 2 个文件
本文关键字:文件 MVC 视图 | 更新日期: 2023-09-27 18:37:24
如何从 MVC 视图将 2 个 Word 文档传递到控制器。
@using (Html.BeginForm("UploadDocument", "Application", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<div class="form-group">
<label for="file1">Please select application document (word file) </label>
<input type="file" name="files" id="file1" class="form-control" />
<label for="file2">Please select support document ( word file )</label>
<input type="file" name="files" id="file2" class="form-control" />
</div>
}
在控制器中
public ActionResult UploadDocument(int Id, IEnumerable<HttpPostedFileBase> files)
{
}
但是我想在控制器内以不同的方式获取 file1 和 file2,以便我可以将其保存到不同的地方。我必须将文件1保存在一个地方,将文件2保存在另一个地方。那么如何确保我单独获取文件呢?
给它们一个单独的唯一名称:
@using (Html.BeginForm("UploadDocument", "Application", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<div class="form-group">
<label for="file1">Please select application document (word file) </label>
<input type="file" name="file1" id="file1" class="form-control" />
<label for="file2">Please select support document ( word file )</label>
<input type="file" name="file2" id="file2" class="form-control" />
</div>
}
控制器:
public ActionResult UploadDocument(int Id, HttpPostedFileBase file1, HttpPostedFileBase file2)
{
// do something with the files
}
更好的方法是将强类型视图与视图模型一起使用:
public class FileUploadViewModel {
HttpPostedFileBase file1 { get; set; }
HttpPostedFileBase file2 { get; set; }
}
视图:
@model MyProject.Models.FileUploadViewModel
@using (Html.BeginForm("UploadDocument", "Application", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<div class="form-group">
<label for="file1">Please select application document (word file) </label>
@Html.TextBoxFor(m => m.file1, null, new { type = "file", id = "file1", @class = "form-control" })
<label for="file2">Please select support document ( word file )</label>
@Html.TextBoxFor(m => m.file2, null, new { type = "file", id = "file2", @class = "form-control" })
</div>
}
控制器:
public ActionResult UploadDocument(int Id, FileUploadViewModel model)
{
// do something with the files
if(model.file1 != null && model.file1.ContentLength > 0) {
// save first file
}
// etc.
}