0

I am doing my project in mvc

i have controller to upload file in to a folder

   public ActionResult UploadFile(HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            if (file == null) { ModelState.AddModelError("File", "Please Upload Your file"); }
            else if (file.ContentLength > 0)
            {
                .................
                else
                {   //Excel file copied temporarily to temp folder
                    var filename = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/Uploads/"), filename);
                    file.SaveAs(path);
                    ModelState.Clear();
                    ViewBag.Message = "File uploaded successfully";

                }
            }
        }
        return RedirectToAction("UploadSTR", "Upload");
    }

and my view is

       @using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
      File Path    put type="file"  name="file" id="file" />
      <input type="submit" name="submit" value="Upload" id="btn" />
}
<p> Message:@ViewBag.Message</p>

my problem is that after submit, file is uploaded and the return to the same page .But ViewBag.Message = "File uploaded successfully" is no shown in my view

neel
  • 5,123
  • 12
  • 47
  • 67

3 Answers3

0

If you use a view model, you can add the message as a hidden form value using the Html.HiddenFor() helper in your view. This way the value would get posted back into the model on form submission. You're probably not going to get the functionality you need using the ViewBag.

The ViewBag has certain uses where it is advantageous to use it, like for setting the page title in a layout. But in general the ViewBag is a beginner level item that you should probably look towards abandoning in favour of view models, to make use of MVC's powerful automatic view model binding features.

Maybe have a run through the MVC Music Store example or Google for other examples of using view models in ASP.NET MVC.

Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69
0

You can not pass data via ViewBag (and ViewData) during redirection, you need to avoid redirection or to use TempData. About TempData you can read here ViewBag, ViewData and TempData .

Community
  • 1
  • 1
Kladzey
  • 411
  • 4
  • 5
0

ViewBag will not survive redirect. Use TempData instead.

free4ride
  • 1,613
  • 1
  • 18
  • 21