MVC: How to post File Upload and other form fields to one action

I had a look in Steve Sanderson’s great book (Pro ASP.NET MVC 2 Framework) and his Sports Store sample application has a file upload form where there are standard form elements mixed with a file upload “multipart/form-data” element. So it looks like the multipart type suffices for all form elements on the page. Although the uploaded image is being saved in the db I’m sure I can do a file.SaveAs() within the same Action. Thanks Mr. Sanderson. Hope you dont mind me reproducing your code…

VIEW

    <asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <h1>Edit <%= Model.Name %></h1>

    <% using (Html.BeginForm("Edit", "Admin", FormMethod.Post, 
                             new { enctype = "multipart/form-data" })) { %>
        <%= Html.Hidden("ProductID") %>
        <p>
            Name: <%= Html.TextBox("Name") %>
            <div><%= Html.ValidationMessage("Name") %></div>
        </p>
        <p>
            Description: <%= Html.TextArea("Description", null, 4, 20, null) %>
            <div><%= Html.ValidationMessage("Description") %></div>
        </p>
        <p>
            Price: <%= Html.TextBox("Price") %>
            <div><%= Html.ValidationMessage("Price") %></div>
        </p>
<p>
    Category: <%= Html.TextBox("Category") %>
    <div><%= Html.ValidationMessage("Category") %></div>
</p>
<p>
    Image:
    <% if(Model.ImageData == null) { %>
        None
    <% } else { %>
        <img src="https://stackoverflow.com/questions/5149116/<%= Url.Action("GetImage", "Products", 
                                 new { Model.ProductID }) %>" />
    <% } %>
    <div>Upload new image: <input type="file" name="Image" /></div>                
</p>

<input type="submit" value="Save" /> &nbsp;&nbsp;
        <%=Html.ActionLink("Cancel and return to List", "Index") %>
    <% } %>
</asp:Content>

CONTROLLER

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Product product, HttpPostedFileBase image)
    {
        if (ModelState.IsValid) {
            if (image != null) {
                product.ImageMimeType = image.ContentType;
                product.ImageData = new byte[image.ContentLength];
                image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            }
            productsRepository.SaveProduct(product);
            TempData["message"] = product.Name + " has been saved.";
            return RedirectToAction("Index");
        }
        else // Validation error, so redisplay same view
            return View(product);
    }

Leave a Comment