最近参考网络资料,学习了ASP.NET MVC如何上传文件。最基本的,没有用jQuery等技术。
1、定义Model
public class TestModel
{ [Display(Name = "标题")] [Required] public string Title { get; set; } [Display(Name = "内容")] [Required] [DataType(DataType.MultilineText)] public string Content { get; set; } public string AttachmentPath { get; set; } }2、Controller
public class TestController : Controller { // // GET: /Test/ public ActionResult Upload() { return View(); } ////// 提交方法 /// /// 模型数据 /// 上传的文件对象,此处的参数名称要与View中的上传标签名称相同 ///[HttpPost] public ActionResult Upload(TestModel tm, HttpPostedFileBase file) { if (file == null) { return Content("没有文件!", "text/plain"); } var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName)); try { file.SaveAs(fileName); //tm.AttachmentPath = fileName;//得到全部model信息 tm.AttachmentPath = "../upload/" + Path.GetFileName(file.FileName); //return Content("上传成功!", "text/plain"); return RedirectToAction("Show",tm); } catch { return Content("上传异常 !", "text/plain"); } } public ActionResult Show(TestModel tm) { return View(tm); } }
3、View
3.1 Upload.cshtml
@model MvcApplication1.Models.TestModel@{ ViewBag.Title = "Upload";}普通上传 @*enctype= "multipart/form-data"是必需有的,否则action接收不到相应的file*@ @using (Html.BeginForm("Upload", "Test", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.LabelFor(mod => mod.Title) @Html.EditorFor(mod => mod.Title) @Html.LabelFor(mod => mod.Content) @Html.EditorFor(mod => mod.Content) 上传文件 }
3.2 Show.cshtml
@model MvcApplication1.Models.TestModel@{ ViewBag.Title = "Show";}Show
@Html.LabelFor(mod => mod.Title)@Html.EditorFor(mod => mod.Title) @Html.LabelFor(mod => mod.Content)@Html.EditorFor(mod => Model.Content)图片: