We help IT Professionals succeed at work.

Passing Error Message from Controller to ViewBag

Crystal Rouse
on
104 Views
Last Modified: 2019-01-27
Trying to figure out how to get a error message to the View Bag.  I have this in my View:

 @if (!string.IsNullOrEmpty(ViewBag.Message))
    {
        <script type="text/javascript">
        swal({
            title: "Error",
            text: "@ViewBag.Message",
            type: "error"
        }, function () {
            url = '@Url.Action("Index", "Requests")';
            window.location.href = url;
        });
        </script>
    }

Open in new window


My Controller has both a Get and a Post and I'm not sure how to get the error message to my View in the ViewBag.Message

[HttpGet]
        public ActionResult Index()
        {

            ViewBag.Message = String.Empty;
            if (!String.IsNullOrEmpty(HttpContext.Session["Error"]?.ToString()))
            {
                ViewBag.Message = HttpContext.Session["Error"].ToString();
                HttpContext.Session.Remove("Error");
            }

            return View();
        }

 [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file, string Name)
        {
            var result = new { Success = "", Message = "" };
            try
                {
                    string pdfTemplate = "NewRequest.pdf";
                    byte[] pdfbytes = null;
                    BinaryReader rdr = new BinaryReader(file.InputStream);
                    pdfbytes = rdr.ReadBytes((int)file.ContentLength);
                    PdfReader reader = new PdfReader(pdfbytes);

                    string t = Name.Trim().Length == 0 ? null : Name;
                    var fields = reader.AcroFields.Fields;
                    var RequestID = reader.AcroFields.GetField("requestId");
                    var OpenDate = reader.AcroFields.GetField("openDate");
                    var Org = reader.AcroFields.GetField("organization");
                    var NeedDate = reader.AcroFields.GetField("needDate");
                    var FirstName = reader.AcroFields.GetField("firstName");
                    var LastName = reader.AcroFields.GetField("lastName");
                     .....
                  
                    tbl_Request request = new tbl_Request()
                    {
                        addedDate = DateTime.Now,
                        title = t,
                        requestId = RequestID,
                        openDate = Convert.ToDateTime(OpenDate),
                        organization = Org,
                        needDate = Convert.ToDateTime(NeedDate),
                        firstName = FirstName,
                        lastName = LastName

                       ..........
                    };

                    myDB.tbl_Request.Add(request);
                    myDB.SaveChanges();
                }
                catch (Exception ex)
                {
                    Utility util = new Utility();
                    string error = util.innerExcep(ex);
                result = new { Success = "False", Message = error };
                return RedirectToAction("Index", "Upload", new { Result = result });
                }

            return RedirectToAction("Index", "Requests", new { });
        }

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
ViewBag's data type is dynamic. That means you won't get any Intellisense on it. Other than that, just assign to it at whatever place in your controller is appropriate:

ViewBag.Message = "Uh-oh!!";

Open in new window

Crystal RouseTask Lead

Author

Commented:
Can you please give an example of how to use it in the View?
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
That's line 1 of your first code snippet.
Crystal RouseTask Lead

Author

Commented:
I tried setting ViewBag.Message = "Test" in the controller.  I get nothing.  
I'm not doing something right here.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Crystal RouseTask Lead

Author

Commented:
Thank you so much for the sample code!

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.