Passing Error Message from Controller to ViewBag

Crystal Rouse
Crystal Rouse used Ask the Experts™
on
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

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
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?
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
That's line 1 of your first code snippet.
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Crystal RouseTask Lead

Author

Commented:
I tried setting ViewBag.Message = "Test" in the controller.  I get nothing.  
I'm not doing something right here.
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Here's a simplified example:

Controller
using System.Web.Mvc;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            ViewModel viewModel = new ViewModel();

            viewModel.Greeting = "Hello World!!";

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Index(ViewModel viewModel)
        {
            if (string.IsNullOrWhiteSpace(viewModel.Greeting))
            {
                ViewBag.Message = "You must supply a greeting!";
            }

            return View(viewModel);
        }
    }

    public class ViewModel
    {
        public string Greeting { get; set; }
    }
}

Open in new window


View
@model WebApplication3.Controllers.ViewModel

@{
    ViewBag.Title = "Home Page";
}


<form method="post" class="container">
    <div class="row">
        <div class="col-md-3">
            <input type="text" name="@nameof(Model.Greeting)" value="@Model.Greeting" />
        </div>
        <div class="col-md-2">
            <label>@Model.Greeting</label>
        </div>
        <div class="col-md-2">
            <button type="submit">Send</button>
        </div>
    </div>
</form>

@if (!string.IsNullOrWhiteSpace(ViewBag.Message))
{
    <script>
        alert('@ViewBag.Message');
    </script>
}

Open in new window


Screenshot
Crystal RouseTask Lead

Author

Commented:
Thank you so much for the sample code!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial