【发布时间】:2019-08-02 09:38:38
【问题描述】:
我有一个 mvc 5 asp.net 文件上传,用于上传图片并为它们创建路径。
文件上传成功,但模型数据确实为空。
这是我的模型:
[Table("Slider")]
public partial class Slider
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Slider()
{
Slider1 = new HashSet<Slider>();
}
public int ID { get; set; }
public string Path { get; set; }
public int? Slider_ID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Slider> Slider1 { get; set; }
}
这是控制器部分:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Path")] Slider slider, List<HttpPostedFileBase> FileContent)
{
if (ModelState.IsValid)
{
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase poImgFile = Request.Files["Path"];
using (var binary = new BinaryReader(poImgFile.InputStream))
{
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
string picturePath = string.Format(Server.MapPath("~/content/slider/{0}.jpg"), slider.ID);
CreateDirectory(picturePath);
using (FileStream writer = new FileStream(picturePath, FileMode.Create))
{
writer.Write(imageData, 0, imageData.Length);
}
db.Sliders.Add(slider);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(slider);
}
这是视图:
@using (Html.BeginForm("Create", "Sliders", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="col-12 form-group">
<div class="row">
@Html.LabelFor(model => model.Path, "Picture", htmlAttributes: new { @class = "control-label col-12 col-md-2" })
<div class="col-12 col-md-10">
<input type="file" name="Path" id="fileUpload" accept=".png,.jpg,.jpeg,.gif" />
@Html.ValidationMessageFor(model => model.Path, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-12 text-left">
<input type="submit" value="create" class="btn btn-success" /> | @Html.ActionLink("back to list", "Index", null, new { @class = "btn btn-primary" })
</div>
</div>
</div>
}
当我检查我的数据库时,我发现路径是:
System.Web.HttpPostedFileWrapper
Slider_ID 为空,Slider_ID1 也为空。
有什么建议吗?
【问题讨论】:
-
我不确定这是否会完全解决它,但是您在提交时没有将 Id 从视图中传回。尝试在@Html.AntiForgeryToken() 正下方添加@Html.HiddenFor(model => model.ID)
-
@LasseHolm 它没有解决我的问题。再次接收null
标签: file-upload asp.net-mvc-5 multipart