无论我尝试什么,我的帖子图片总是为null或对象引用未设置为对象的实例。
我有一个映射到表格的帖子类和图像类(首先使用EF代码)
这是我的代码:
查看:
<h2>Create</h2>
@using (Html.BeginForm("Create", "Admin", FormMethod.Post, new{ enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
@Html.LabelFor(post => post.Post.Blog)
@Html.DropDownListFor(post => post.Post.BlogId, Model.BlogList)
@Html.LabelFor(post => post.Post.Category)
@Html.DropDownListFor(post => post.Post.CategoryId, Model.CategoryList)
@Html.LabelFor(post => post.Post.Title)
@Html.EditorFor(post => post.Post.Title)
<br />
@Html.LabelFor(post => post.Post.Content)
@Html.EditorFor(post => post.Post.Content)
<br />
<input type="file" name="uploadImage" value="Upload" />
<input type="submit" value="Create" />
}
行动方法:
[HttpPost]
public ActionResult Create(Post post, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
var postBlog = _repository.Blogs.Single(b => b.BlogId == post.BlogId);
post.Created = DateTime.Now;
postBlog.Posts.Add(post);
PostImage newImage = new PostImage()
{
MimeType = image.ContentType,
ImageData = new byte[image.ContentLength],
PostId = post.PostId
};
_repository.AddImage(newImage);
_repository.Save();
return RedirectToAction("Index");
}
答案 0 :(得分:3)
卫生署!问题是我在input元素中设置了'value'你只需输入type =“file”name =“Image”/&gt;让它正确绑定