Passing Viewbag Data from View to Controller in ASP.Net MVC3 Razor

asp.net-mvc-3, entity-framework, image, razor

Solution

ViewBag can't pass data back to controller. You should post those values back inside the form. Easiest thing would be to not to use ViewBag and add the data to model type.

Then you can pass them with hidden inputs using HTML helpers like this:

@Html.HiddenFor(item => item.CustomerId)
@Html.HiddenFor(item => item.ImageId)

If that's not possible, you can add the hidden inputs manually. Just keep in mind that the name attributes are important for model binding.

<input type="hidden" name="CustomerId" value="@ViewBag.Data1" />

Problem

In my ASP.Net MVC3 Razor project i have to pass value from view to controller.The view contains one submit button that is used to pass selected image file and two other input data.This two input data is from a controller named "FileUpload"(ViewBag.Data1 = CusId;ViewBag.Data2 = Name;).When submitting the button i have to pass these three (Image,CusId,Name) to another controller to upload the image file. Controller Code ``` public ActionResult FileUpload(int CusId, string Name) { ViewBag.Data1 = CusId; ViewBag.Data2 = Name; return View(); } [HttpPost] public ActionResult UploadPhoto(ElixiCustPro elixi, HttpPostedFileBase file) { //return null; try { if (file != null && file.ContentLength > 0) { if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") || (file.ContentType == "image/png"))//check allow jpg, gif, png { elixi.Image = new byte[file.ContentLength]; file.InputStream.Read(elixi.Image, 0, file.ContentLength); var filename = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/ElixirFiles/UploadImagesElixir/"), filename); file.SaveAs(path); ecp.Image = new byte[file.ContentLength]; ecp.ImageUrl = path; ment.ElixiProData.Add(ecp); ment.SaveChanges(); return RedirectToAction("ImageResult"); } } } catch (Exception ex) { return View(ex.Message.ToString()); } return View(); } ``` View Code ``` @using (Html.BeginForm("UploadPhoto", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" })) { @* <div class="form-group"> <label class="col-lg-2 control-label"> Customer ID</label> <div class="col-lg-10">@Html.TextBoxFor(model => model.CusId, new { @class = "form-control" })</div> <label class="col-lg-2 control-label"> Customer Name</label> <div class="col-lg-10">@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })</div> </div>*@ <input type="hidden" id="id" /> <div class="col-md-6"> <div class="form-group"> <label class="col-lg-2 control-label"> DMIT Image</label> <div class="col-lg-10"> @ViewBag.Data1 @ViewBag.Data2 <input type="file" id="file" name="file"> <input type="submit" class="btn btn-success" value="Upload" /> </div> </div> </div> } ```

Original source