Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading multiple images in the same form using MVC3

Here is my controller code and also my View:

@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" })) {
    @Html.ValidationSummary()

    <div class="form-field">
        <p>@Html.LabelFor(m => m.Name)</p>
        @Html.EditorFor(m => m.Name)
    </div>

    <div class="form-field">
        <p>@Html.LabelFor(m => m.Description)</p>
        @Html.EditorFor(m => m.Description)
    </div>

    <div class="form-field">
        <p>@Html.LabelFor(m => m.UnitPrice)</p>
        @Html.EditorFor(m => m.UnitPrice)
    </div>

    <div class="form-field">
        <input type="file" name="image1" />
        <input type="file" name="image2" />
        <input type="file" name="image3" />
    </div>

    <div class="form-field">
        <input type="submit" value="Create" />
    </div>
}

And in the Controller. Don't focus on the content of the action method, just focus on the parameter of type List<HttpPostedFileBase>. Is this the right way of doing things? As it is, images is null upon submission of the form.

[HttpPost]
public ActionResult Create(ProductModel model, List<HttpPostedFileBase> images)
{
    try
    {
        if (ModelState.IsValid)
        {
            var newProduct = Mapper.Map<ProductModel, Product>(model);
            _productRepository.CreateProduct(newProduct);
            _productRepository.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch
    {
        return View(model);
    }
}

If you could provide a very simple example that would be fantastic.

like image 717
Only Bolivian Here Avatar asked Jan 13 '12 02:01

Only Bolivian Here


2 Answers

OK, so this is a simple example on how to do it. The end result:

enter image description here

The HTML markup is a simple form, with a submit button.

@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" })) {
    @Html.ValidationSummary()

    <div class="form-field">
        <p>Select pictures:</p>
        <div class="upload-container">
            <div class="upload">
                <input type="file" name="files" id="file1" /> 
                <img src="@Url.Content("~/Public/images/delete.png")" alt="Remove picture." />
            </div>
        </div>        
    </div>

    <div class="form-field">
        <input type="submit" value="Create" />
    </div>
}

We also needs some jQuery magic so that every time someone adds an image, we let them also add in more as needed. A user can upload N images.

<script type="text/javascript">
    $(document).ready(function () {
        var currentImage = 1;
        $("body").on("change", "input[name='files']", function () {
            var pathToRemoveIcon = "@Url.Content("~/Public/images/delete.png")";
            currentImage = currentImage + 1;
            var htmlToAppend = '<div class="upload"><input type="file" name="files" id="file' + currentImage + '" /><img src="' + pathToRemoveIcon + '" alt="Remove picture." /></div>';
            $('.upload-container').append(htmlToAppend);
        }).on("click", ".upload img", function () {
            if ($(this).parent().siblings().length > 0) {
                $(this).parent().remove();    
            }
        });
    });
</script>

And finally the controller code:

[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
    try
    {
        if (ModelState.IsValid)
        {
            //Persist the files uploaded.
        }
        return RedirectToAction("Index");
    }
    catch
    {
        return View(model);
    }
}
like image 146
Only Bolivian Here Avatar answered Oct 05 '22 20:10

Only Bolivian Here


Look at these two posts they might help

ASP.NET MVC: ModelBinding Multiple File Uploads to an Array

Uploading a File (Or Files) With ASP.NET MVC

like image 45
Maheep Avatar answered Oct 05 '22 22:10

Maheep