Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
                    }
like image 340
Nidheesh Avatar asked Jan 29 '14 09:01

Nidheesh


People also ask

How do I pass ViewBag data from view to controller?

ViewBag itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.

How do I get ViewBag data in Cshtml?

cshtml view, you can access ViewBag. TotalStudents property, as shown below. Internally, ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.


2 Answers

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" />
like image 73
Ufuk Hacıoğulları Avatar answered Jan 14 '23 14:01

Ufuk Hacıoğulları


Yes you cannot pass a Viewbag from view to controller. But you can pass them using TempData.

Add this to your View.

@{TempData["Data1"]=ViewBag.Data1}
@{TempData["Data2"]=ViewBag.Data2}

But this TempData passes the information as an object. So typecasting is necessary in your Controller.

int x=Convert.ToInt32(TempData["Data1"]);
string y=(TempData["Data2"]).ToString();

I tried,it is working.

or you can send TempData from Controller in get method,and use the same to pass from view to post method instead of Viewbag.

like image 36
Kranthi Kumar Avatar answered Jan 14 '23 15:01

Kranthi Kumar