c# – 在Ajax.BeginForm MVC 4场景中发送异常消息

前端之家收集整理的这篇文章主要介绍了c# – 在Ajax.BeginForm MVC 4场景中发送异常消息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含ajax表单的局部视图.视图只是添加和更新用户信息.

控制器将相同的部分视图发送回ActionResult.

我想要做的是在事务不成功时显示错误消息.但是它仍然应该发回部分视图,这次只发送一条消息.

如何实现?

码:

ManageUsers.cshtml

<div id="details">
@{
    Html.RenderPartial("AddModifyUserPartialView");
}
</div>

@{
    Html.RenderPartial("ListUsersPartialView");
 }

AddModifyUserPartialView.cshtml

@using (Ajax.BeginForm("AddModifyUser","Account",FormMethod.Post,new AjaxOptions() 
         { 
             UpdateTargetId = "details",OnFailure= "handleError",OnSuccess="handleSuccess" 
         },new { id = "useragentform",enctype = "multipart/form-data" }))
{
  //form fields here
  <input type="submit" id="savebutton" name="savebutton" value="Add New User" />
}

另外在局部视图中:

function handleError(ajaxContext) {

    var response = ajaxContext.get_response();
    var statusCode = response.get_statusCode();

    alert(statusCode);
}

账户管理员

try
{
     SecurityManager.AddUpdateUserAgent(ua);
}
catch (Exception ex)
{
     //how do I send the message back along with the partial view???
}
return PartialView("AddModifyUserPartialView");

解决方法

解决这个问题的两个部分,创建一个新的异常,让我们用你的消息称它为StatusException,并在你发现正常异常时抛出它:
try
{
   SecurityManager.AddUpdateUserAgent(ua);
}
catch (Exception ex)
{
   throw new StatusException("Your error message here")
} 
return PartialView("AddModifyUserPartialView");

覆盖Controller :: OnException并通过将其设置为handling来处理异常,将错误代码设置为500,将HttpContext.Response.StatusDescription设置为StatusException消息.例如:

protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception == null) return;

        Type exceptionType = filterContext.Exception.GetType();

        if (exceptionType == typeof(StatusException))
        {

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8;
            filterContext.HttpContext.Response.HeaderEncoding = Encoding.UTF8;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
        }
     }

然后,在Ajax.BeginForm的OnFailure处理程序中,显示错误参数:

function handleError(data){
    //display data.errorThrown,data.statusCode,etc...
}

通过在OnException覆盖中将错误代码设置为500,AjaxForm将检测错误跳转到您的处理程序.我们也在覆盖中设置StatusDescription,以便在handleError回调中提供该消息.

猜你在找的C#相关文章