使用HttpPostedFileBase在视图模型上表示上传的文件会更有意义,而不是string
:
public class DR405Model
{
[DataType(DataType.Text)]
public string TaxPayerId { get; set; }
[DataType(DataType.Text)]
public string ReturnYear { get; set; }
public HttpPostedFileBase File { get; set; }
}
那么你可以有以下视图:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
... input fields for other view model properties
<div class="editor-field">
<%= Html.EditorFor(model => model.File) %>
<%= Html.ValidationMessageFor(model => model.File) %>
</div>
<input type="submit" value="OK" />
<% } %>
最后在里面定义对应的编辑器模板~/Views/Shared/EditorTemplates/HttpPostedFileBase.ascx
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<input type="file" name="<%: ViewData.TemplateInfo.GetFullHtmlFieldName("") %>" id="<%: ViewData.TemplateInfo.GetFullHtmlFieldId("") %>" />
现在控制器可能如下所示:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new DR405Model());
}
[HttpPost]
public ActionResult Index(DR405Model model)
{
if (model.File != null && model.File.ContentLength > 0)
{
var fileName = Path.GetFileName(model.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
model.File.SaveAs(path);
}
return RedirectToAction("Index");
}
}