模型
public partial class Assignment { public Assignment() { this.CourseAvailables = new HashSet<CourseAvailable>(); } public string AssignmentID { get; set; } public Nullable<System.DateTime> SubmissionDate { get; set; } public string Status { get; set; } public Nullable<decimal> Mark { get; set; } public string Comments { get; set; } public string FileLocation { get; set; } public virtual ICollection<CourseAvailable> CourseAvailables { get; set; } }}
控制者
public ActionResult Create(Assignment assignment) { if (ModelState.IsValid) { db.Assignments.Add(assignment); db.SaveChanges(); return RedirectToAction("Index"); } return View(assignment); }
视图
<div class="editor-field"> <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%> <%: Html.ValidationMessageFor(model => model.FileLocation) %> </div>
如果要将文件存储到服务器/路径文件夹中,并且仅在数据库中存储路径名/字符串,如何存储文件。
您可以上传文件并将其网址保存在数据库表中,如下所示:
@using(Html.BeginForm("Create","Assignment",FormMethod.Post,new {enctype="multipart/form-data"})) { ... <div class="editor-field"> <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%> <%: Html.ValidationMessageFor(model => model.FileLocation) %> </div> ... }
[HttpPost] public ActionResult Create(Assignment assignment) { if (ModelState.IsValid) { if(Request.Files.Count > 0) { HttpPostedFileBase file = Request.Files[0]; if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); assignment.FileLocation = Path.Combine( Server.MapPath("~/App_Data/uploads"), fileName); file.SaveAs(assignment.FileLocation); } db.Assignments.Add(assignment); db.SaveChanges(); return RedirectToAction("Index"); } } return View(assignment); }
为了更好地理解,请参考 这篇出色的文章,使用ASP.NET MVC上传文件(或多个文件)