1

Im trying to show the message from an exception on one of my views using a ViewBag property. However, no matter what I put in the ViewBag property it does not show in my view.

I have tried sending the exception and a simply string, this is the method from the controller:

        public ActionResult Create([Bind(Include="IDHardware,PartNo,SerialNo,CatagoryType,IsOnLoan")] Hardware hardware)
    {
        if (ModelState.IsValid)
        {
            try
            {
                db.Hardwares.Add(hardware);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                ViewBag.ErrMsg = exceptionMessage;


                return RedirectToAction("BarcodeNotUnique");
            }

        }

        ViewBag.CatagoryType = new SelectList(db.Catagories, "CatagoryName", "CatagoryName", hardware.CatagoryType);
        return View(hardware);

And this is the html from the view BarcodeNotUnique:

    @model TechDemoStockWebsite.Models.Hardware

@{
    ViewBag.Title = "BarcodeNotUnique";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="jumbotron">
    <h1>@ViewBag.ErrMsg</h1>
    <h1>@ViewBag.example</h1>
    <p class="lead"> @Html.ActionLink("Please try again", "Create")</p>
    <p class="lead"> or return to list of @Html.ActionLink("available hardware", "Index")</p>

</div>

Any ideas?

BR

Chris

user1870218
  • 45
  • 1
  • 6

1 Answers1

2

Anything in ViewData gets lost if you do a redirect. In your code, you are setting a property on ViewData and then performing return RedirectToAction("BarcodeNotUnique");. If you really need to do a redirect, you can use TempData instead.

See this question for more details about ViewData and TempData: ViewBag, ViewData and TempData

Community
  • 1
  • 1
David Spence
  • 7,999
  • 3
  • 39
  • 63