MVC 3: Creating a new model instance from within another model's edit page and adding it to the parent
I've been having trouble figuring out how to best implement an image gallery editing page allowing the user to upload pictures directly into the gallery in an MVC 3 project for my friend. I've tried searching around, but there doesn't seem to b开发者_StackOverflowe any solid documentation on what I'm looking for.
Once the user has created the gallery, the controller redirects them to the edit page where I'd like to let the user upload a new image into the gallery. Once it's uploaded, I could add it to the gallery model, refresh the page, and have it display in the list along with the other images.
I'm having trouble figuring out how to handle the uploading portion. I'm pretty sure it should be a separate action from the "save changes" action, but I have no idea if I should implement the uploader as a partial view, a child action, or something else I haven't heard of yet.
My gut feeling is to go with a partial view, but when I do this, I can't figure out how to get the strongly-typed gallery object of the hosting page so I can properly add the image to the correct gallery in the partial view.
Any ideas how to properly implement something like this?
Well, the solution turned out to be easier than I thought.
I created a new ActionResult called UploadImage:
[HttpPost]
public ActionResult UploadImage()
{
string galleryId = Request.Form["GalleryId"];
string title = Request.Form["ImageTitleField"];
string description = Request.Form["ImageDescriptionField"];
HttpPostedFileBase imageUpload = Request.Files["ImageUploadField"];
return RedirectToAction("Edit", new { new Guid(galleryId) });
}
Then I created a partial view for it bound to the ImageGallery model, which I rendered using @Html.Partial("UploadImage", Model)
outside of the Edit page's main form. The partial view just contains two text fields, title and description, as well as a file upload field. It also includes a hidden field that takes the bound ImageGallery's Id property.
When the user clicks 'Upload', the above method fires allowing me to generate a new Image model and add it to the appropriate ImageGallery entry using the Id field passed into the partial view. After the image is uploaded, the user is redirected to the same Edit page where the uploaded image is displayed in a list along with other images.
精彩评论