ozsenegal
ozsenegal

Reputation: 4133

ASP.MVC handle errors

In ASP.NET Web Forms,i would accomplish that easily:

[...]
try
{
    DateTime date = Convert.ToDateTime("abc");
}
catch(Exception ex)
{
   lblErrorMessage.Text = ex.Message;
}

Now the question is:How can i do the same in ASP.NET MVC? Ive been looking for it and all i found is [HandleError] attribute.I dont want to redirect user to a "Error.aspx" View if an exception occurs.I want to show error messages in the same page like in Web Forms.

Any Ideias?

Upvotes: 0

Views: 155

Answers (3)

Sruly
Sruly

Reputation: 10540

try 
{ 
    DateTime date = Convert.ToDateTime("abc"); 
} 
catch(Exception ex) 
{ 
   ModelState.AddModelError("date", ex)
} 

then in the view

<%= Html.ValidationSummary() %>

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

Create your own attribute which implements IExceptionFilter. You could also return the same View, and set a value in the ViewData, but an attribute would give you a more standard way to handle it.

Upvotes: 0

Tommy
Tommy

Reputation: 39807

try
{
    DateTime date = Convert.ToDateTime("abc");
}
catch(Exception ex)
{
   ViewData["Error"] = ex.Message;
}
return View();

In your view or master page, check to see if ViewData["Error"] is set. If so, display your error div.

<% if (ViewData["Error"] != null)
{
    <div class="error"><%=html.encode(ViewData["Error"]) %></div>
}
%>

Upvotes: 2

Related Questions