這將更有意義使用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");
}
}
MVC4 - 我一直想知道爲什麼DataType.Upload不呈現類型=「文件」 – felickz 2012-10-04 05:29:50