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