如何从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,这样我就可以将它保存到不同的地方。我必须将File1保存在一个地方,将file2保存在另一个地方。那么我怎么能确保我得到文件呢?
答案 0 :(得分: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
}
更好的方法是使用带有viewmodels的强类型视图:
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.
}