Obak Shibly
Obak Shibly

Reputation: 65

Passing error message from controller to view

I want to do something like below.

//Controller

if(Session["UserId"]!=null)  // If user is logged in
{
   return View(db.Orders.ToList());
}
else
{
    //return a error message on the same view
}

how can i do this??

Upvotes: 1

Views: 4386

Answers (3)

ModelState.AddModelError("Error", ex.Message);

There is a default validation summary div that display the exception encountered. Otherwise the viewbag would be preferable as you create your own display.

Upvotes: 0

Musikero31
Musikero31

Reputation: 3153

Not sure if you still need this, but what I would do is to throw the HttpException and let my ajax call handle it.

Example:

try
{
  // DO SOMETHING....
}
catch (Exception ex)
{
  //Note: I use Bad Request status code for this example. You can choose what is specific for your needs...
  throw new HttpException((int)HttpStatusCode.BadRequest, ex.Message, ex.InnerException); 
}

Upvotes: 0

krivtom
krivtom

Reputation: 24916

Ideally you would use a view model and have a property for error message there. If you are not using a view model, you could add a value to your ViewBag and use it in the view:

if(Session["UserId"]!=null)  // If user is logged in
{
    return View(db.Orders.ToList());
}
else
{
    ViewBag.ErrorMessage = "My error message";
}

In your view you would use the added value somewhere:

<p>@ViewBag.ErrorMessage</p>

Upvotes: 1

Related Questions