Michael Harper
Michael Harper

Reputation: 1531

MVC 4 HttpPostedFileBase always null

No matter what I try my post images are always null or Object reference not set to an instance of an object.

I have a post class and images class that map to tables (Using EF code first)

Here's my code:

View:

<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" />
}

Action Method:

  [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");

        }

Upvotes: 1

Views: 3335

Answers (1)

Michael Harper
Michael Harper

Reputation: 1531

Doh! the problem was I had set 'value' in the input element you only need input type="file" name="Image" /> for it to bind correctly

Upvotes: 3

Related Questions