The following worked for me.
Model:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var fileName = Path.GetFileName(model.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
model.File.SaveAs(path);
return RedirectToAction("Index");
}
}
View:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<input type="file" name="file" />
<%= Html.ValidationMessageFor(x => x.File) %>
<input type="submit" value="OK" />
<% } %>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…