自定义错误消息MVC

时间:2015-07-03 09:49:21

标签: asp.net asp.net-mvc razor error-handling asp.net-mvc-5

处理ASP.Net Web Forms&的混合项目。 MVC。

场景:在Web窗体应用程序中,页面的一部分使用MVC部分视图进行渲染,如下图所示。

enter image description here

在Web窗体 aspx 页面中,定义了ID为ID = MVCPartialView1的Div,并成功使用Jquery Ajax可以将返回的部分视图绑定到Web窗体。

 $.ajax(
 {
 success: function (msg) { $("#MVCPartialView1").html(msg); }
});

For Handling Error Scenario使用以下代码。

[AttributeUsage(AttributeTargets.Class)]
    public sealed class ErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            // Execute the normal exception handling routine
            base.OnException(filterContext);

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "CustomError.aspx"
                };
            }
        }
    }

基础控制器:

[ErrorAttribute]
public class BaseController : Controller

实际问题是当MVC部分视图(Controller)中发生任何异常时,CustomError仅显示在DIV MVCPartialView1内,但将CustomError显示为完全包含WebForm.aspx

是有意义的

enter image description here

但是预期的CustomError消息是:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以在场景中仅使用js。

有些事情是这样的:

$.ajax(
{
   success: function (msg) 
   {
      if(msg.indexOf("Error") > -1) //You should check if Error page returned
      {
         window.location.href = "CustomError.aspx"; //Here if redirect to error of full page
      }
      else
      {
        $("#MVCPartialView1").html(msg); 
      }   
   }
});