@using (Html.BeginForm(new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) <fieldset> <legend>Question</legend> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Title, new { style = "width: 400px" }) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> 添加问题图片: </div> <div class="editor-field"> 选择上传文件:<input name="file" type="file" id="file" /> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> }
controller:
// POST: /Question/Create Question question,
[HttpPost] public ActionResult Create(Question question, HttpPostedFileBase file) { try { if (ModelState.IsValid) { if (file !=null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Resources"), fileName); file.SaveAs(path); QuestionResource resource = new QuestionResource(); resource.Url = path; question.Resources.Add(resource); } unitOfWork.QuestionRepository.Insert(question); unitOfWork.Save(); return RedirectToAction("Index"); } } catch(Exception ex) { //Log the error (add a variable name after DataException) ModelState.AddModelError("", question.Title + " " + question.Description + " " + file.ContentLength + " " + ex.Message + " Unable to save changes."); } return View(question); }
在控制器中:HttpPostedFileBase file获取不到上传的文件。调试显示null。
如何获取到上传的文件?谢谢
守着一只汪
蝴蝶不菲
慕森王
慕容森
aluckdog