2010-10-02 80 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) { 
    } 
});