You'll need to:
- add an
input
of typefile
to your form, - have the attribute on your form element
enctype = "multipart/form-data"
Then add an HttpPostedFileBase
to your model with the same name as the name of the input
. Then the HttpPostedFileModelBinder
will populate the model property from the uploaded file before the action is invoked. Note, I think you should probably add in the model id somewhere, perhaps as a path element, to guaranteed uniqueness in the image path so that images don't accidentally get overwritten.
There's a reasonably complete discussion of this at http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files
public class Cakes
{
...
public HttpPostedFileBase UploadedFile { get; set; }
}
[HttpPost]
public ActionResult Edit(Cakes cake) // I'd probably use a view model here, not the domain model
{
if (ModelState.IsValid)
{
if (cakes.UploadedFile != null)
{
cakes.UploadedFile.SaveAs(Path.Combine("path-to-images-for-this-cake", cakes.CakeImage));
}
....
}
}