2010-10-02 43 views
0

假设你有下面的控制器操作如何在ajax调用中处理不同的结果?

[HttpPost] 
public ActionResult Save(CustomerModel model) 
{ 
    if (!ModelState.IsValid) { 
     //Invalid - redisplay form with errors 
     return PartialView("Customer", model); 
    } 
    try { 
     // 
     // ...code to save the customer here... 
     // 
     return PartialView("ActionCompleted"); 
    } 
    catch (Exception ex) { 
     ActionErrorModel aem = new ActionErrorModel() { 
      Message = ex.Message 
     }; 
     return PartialView("ActionError", aem); 
    } 
} 

而且假设你使用jQuery调用这个动作:

$.ajax({ 
    type: "post", 
    dataType: "html", 
    url: "/Customer/Save", 
    sync: true, 
    data: $("#customerForm").serialize(), 
    success: function(response) { 
     /* 
      ?????? 
     */ 
    }, 
    error: function(response) { 
    } 
}); 

我希望能够我正在处理他们的成果来区分客户端上的不同方式。换句话说,我怎么能明白,行动

  • 返回相同的模型,因为还没有通过验证
  • 返回的表示错误信息的意见/邮件

任何建议吗?

回答

2

一种方式来处理,这是附加一个自定义HTTP标头,表示在这种情况下,我们正在下降:

[HttpPost] 
public ActionResult Save(CustomerModel model) 
{ 
    if (!ModelState.IsValid) { 
     //Invalid - redisplay form with errors 
     Response.AppendHeader("MyStatus", "case 1"); 
     return PartialView("Customer", model); 
    } 
    try { 
     // 
     // ...code to save the customer here... 
     // 
     Response.AppendHeader("MyStatus", "case 2"); 
     return PartialView("ActionCompleted"); 
    } 
    catch (Exception ex) { 
     ActionErrorModel aem = new ActionErrorModel() { 
      Message = ex.Message 
     }; 
     Response.AppendHeader("MyStatus", "case 3"); 
     return PartialView("ActionError", aem); 
    } 
} 

而且在客户端测试这个头:

success: function (response, status, xml) { 
    var myStatus = xml.getResponseHeader('MyStatus'); 
    // Now test the value of MyStatus to determine in which case we are 
} 

这样做的好处是,自定义无论您返回哪种内容类型,始终都会在响应中设置HTTP标头。它还将与JSON,XML,工作...

注1:为了避免混乱,你与所有那些Response.AppendHeader指令控制器动作,您可以编写一个定制ActionResult允许你直接指定该头的值,让你简单地return this.MyPartialView("Customer", model, "case 1")

备注2:从请求中删除此sync: true属性,因为它会让我的眼睛受伤(其实我认为你的意思是async: 'false')。

+0

+1 - 正在输入这个,可能是最好的方法。 – 2010-10-02 10:36:47

+0

非常好!我无法想象一个更清洁的方式!无论如何,这使我改变了每一个行动。我猜如果这可以在ActionFilter属性中以自动方式与尼克答案混合完成...... P.S. :)是的,它是'async:'false'' – Lorenzo 2010-10-02 10:46:00

0

你可以检查特有的视图中的元素,例如:

$.ajax({ 
    type: "post", 
    dataType: "html", 
    url: "/Customer/Save", 
    sync: true, 
    data: $("#customerForm").serialize(), 
    success: function(response) { 
     var resp = $(response); 
     if($(resp.find("#customer").length) { 
      //customer returned 
     } else if($(resp.find("#completed").length) { 
      //completed view 
     } else if($(resp.find("#error").length) { 
      //error view 
     } 
    }, 
    error: function(response) { 
    } 
});