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.
OK, so this is a simple example on how to do it. The end result:
The HTML markup is a simple form, with a submit button.
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.
And finally the controller code: