发送异常消息在Ajax.BeginForm MVC 4方案 [英] Send exception message in Ajax.BeginForm MVC 4 scenario

查看:113
本文介绍了发送异常消息在Ajax.BeginForm MVC 4方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个Ajax形式的局部视图。该视图简单的添加和更新用户信息。

控制器发送同一局部视图向后的ActionResult。

我想要做的是显示错误消息,如果交易没有成功。但它仍然应该发回的局部视图,只有这一次的消息。

这将如何实现?

code:

ManageUsers.cshtml

 < D​​IV ID =细节>
@ {
    Html.RenderPartial(AddModifyUserPartialView);
}
< / DIV>

@ {
    Html.RenderPartial(ListUsersPartialView);
 }
 

AddModifyUserPartialView.cshtml

  @using(Ajax.BeginForm(AddModifyUser,账户,FormMethod.Post,
         新AjaxOptions()
         {
             UpdateTargetId =细节,
             OnFailure =handleError的,
             的onSuccess =handleSuccess
         },
         新的id {=useragentform,
               ENCTYPE =的multipart / form-data的}))
{
  //形式在这里领域
  <输入类型=提交ID =savebuttonNAME =savebuttonVALUE =添加新用户/>
}
 

另外,在局部视图:

 函数handleError的(ajaxContext){

    变种响应= ajaxContext.get_response();
    VAR状态code = response.get_status code();

    警报(状态code);
}
 

帐户控制

 尝试
{
     SecurityManager.AddUpdateUserAgent(UA);
}
赶上(例外前)
{
     //我怎么发邮件发回随着局部视图???
}
返回PartialView(AddModifyUserPartialView);
 

解决方案

两部分,以解决这一点,创建一个新的异常,我们称之为StatusException,您的邮件,并把它当你已经抓住了常规异常:

 尝试
{
   SecurityManager.AddUpdateUserAgent(UA);
}
赶上(例外前)
{
   抛出新StatusException(在这里你的错误消息)
}
返回PartialView(AddModifyUserPartialView);
 

覆盖控​​制器:: onException的,并通过将其设置为处理,设置错误code至500,该HttpContext.Response.StatusDescription设置为您StatusException信息处理异常。例如:

 保护覆盖无效onException的(ExceptionContext filterContext)
    {
        如果(filterContext.Exception == NULL)回报;

        键入exceptionType = filterContext.Exception.GetType();

        如果(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.Status code = 500;
            filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
        }
     }
 

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

 函数handleError的(数据){
    //显示data.errorThrown,data.status code,等...
}
 

通过设置错误code至500的onException的覆盖,当作ajaxForm将检测到错误并跳转到您的处理程序。我们设置覆盖的状态说明一样,所以该消息将在handleError的回调可用。

I have a partial view that contains an ajax form. The view simply adds and updates user information.

The controller sends the same partial view back as ActionResult.

What I want to do is to display an error message if the transaction was not successful. But it should still send back the partial view, only this time with a message.

How would this be achieved?

Code:

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" />
}

Also in the partial view:

function handleError(ajaxContext) {

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

    alert(statusCode);
}

Account Controller

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

解决方案

Two parts to solving this, create a new exception, let's call it StatusException, with your message, and throw it when you've caught the normal exception:

try
{
   SecurityManager.AddUpdateUserAgent(ua);
}
catch (Exception ex)
{
   throw new StatusException("Your error message here")
} 
return PartialView("AddModifyUserPartialView");

Override Controller::OnException and handle the exception by setting it to handled, setting the error code to 500, setting the HttpContext.Response.StatusDescription to your StatusException message. For example:

    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;
        }
     }

Then, in your OnFailure handler for Ajax.BeginForm, display out the error parameter:

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

By setting the error code to 500 in the OnException override, AjaxForm will detect an error and jump into your handler. We set the StatusDescription in the override as well, so that message will be available in the handleError callback.

这篇关于发送异常消息在Ajax.BeginForm MVC 4方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆