3
Reply

MVC 5 - Edit View Multiple Actions

manikandan r

manikandan r

Nov 11 2016 7:21 PM
286
I have implemented CRUD functionality in ASP.NET MVC5 application.
 
In my Edit View, I have few text input fields and a upload file button.
 
My Question is with my Upload file and Save Button. How do i achieve both inputs and upload file in same actionresult?  Let me know any other good coding practice to achieve this.
 
Below is my Edit ActionResult:
[HttpGet]         public ActionResult Edit(int? id)         {             if (id == null)                 return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);                 Product product = objDBContext.Products.Find(id);                 if (product == null)                       return HttpNotFound();                 else                     return View(product);         }

 [HttpPost]        public ActionResult Edit(HttpPostedFileBase file)        {            try            {                if (file.ContentLength > 0)                {                    var fileName = Path.GetFileName(file.FileName);                    var path = Path.Combine(Server.MapPath("~\\App_Data\\Images"), fileName);                    file.SaveAs(path);                }                ViewBag.Message = "Upload successful";                return RedirectToAction("Index");            }            catch            {                ViewBag.Message = "Upload failed";                return RedirectToAction("Uploads");            }        } 

Maintaining the upload button in Edit View itself as below:
<div class="form-group">             @Html.Label("Upload Image", new { @class = "control-label col-md-2" })             <fieldset>                 <div class="editor-field">                     @Html.TextBox("file", "", new { type = "file" })                 </div>                 <div class="editor-field">                     <input type="submit" value="Upload" />                 </div>             </fieldset>         </div>
<div class="form-group">             <div class="col-md-offset-2 col-md-10">                 <input type="submit" value="Save" class="btn btn-default" />             </div>         </div>
 

Answers (3)