简体   繁体   English

ASP.MVC处理错误

[英]ASP.MVC handle errors

In ASP.NET Web Forms,i would accomplish that easily: 在ASP.NET Web窗体中,我可以轻松完成此操作:

[...]
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? 现在的问题是:如何在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. 我一直在寻找它,我发现的只是[HandleError]属性。如果发生异常,我不想将用户重定向到“ Error.aspx”视图。我想在同一页面中显示错误消息,例如Web窗体。

Any Ideias? 有任何想法吗?

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. 在视图或母版页中,检查是否设置了ViewData [“ Error”]。 If so, display your error div. 如果是这样,请显示您的错误div。

<% if (ViewData["Error"] != null)
{
    <div class="error"><%=html.encode(ViewData["Error"]) %></div>
}
%>
try 
{ 
    DateTime date = Convert.ToDateTime("abc"); 
} 
catch(Exception ex) 
{ 
   ModelState.AddModelError("date", ex)
} 

then in the view 然后在视图中

<%= Html.ValidationSummary() %>

Create your own attribute which implements IExceptionFilter . 创建自己的实现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. 您也可以返回相同的View,并在ViewData中设置一个值,但是属性可以为您提供更标准的处理方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM