I am trying to allow a user to upload an image to our site, and I'm not quite sure how to use it. I tried using several types to define the image, including System.Drawing.Image and HttpPostedFileWrapper , but @Html.EditorFor always (clearly) displays its attributes as editable fields.
In my opinion, I had, instead of @Html.EditorFor , I had <input type="file" name="imageToUpload" /> , but it did not work out before my presentation as part of the Model ? I am new to MVC, so I hope this is something trivial.
Here is my view:
@using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>New Image</legend> <div class="editor-label"> @Html.LabelFor(model => model.Description) </div> <div class="editor-field"> @Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div> <div class="editor-label"> @Html.LabelFor(model => model.Image) </div> <div class="editor-field"> <input type="file" name="imageToUpload" /> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> }
My controller:
[HttpPost] public ActionResult CreateImage(string brand, string collection, ImageEditViewModel imageEditViewModel) { string fileName = Guid.NewGuid().ToString(); string serverPath = Server.MapPath("~"); string imagesPath = serverPath + String.Format("Content\\{0}\\Images\\", Helper.Helper.ResolveBrand()); string newLocation = Helper.Helper.SaveImage(fileName, imagesPath, imageEditViewModel.Image.InputStream) Image image = new Image { Collection = ds.Single<Collection>(c => c.Season == collection && c.Brand.Name == brand), Description = imageEditViewModel.Description, Location = "newLocation", Order = Helper.Helper.GetImageOrder(brand, collection) }; ds.InsertOnSubmit<Image>(image); ds.SubmitChanges(); return RedirectToAction("Brand"); }
And finally, ViewModel:
public class ImageEditViewModel { public int CollectionId { get; set; } public string Description { get; set; } public HttpPostedFileWrapper Image { get; set; } public int Order { get; set; } }
source share