假设您有以下控制器操作
[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) {
}
});
我希望能够区分我在客户端以不同方式处理它们的结果。换句话说,我怎么能理解这个动作
有什么建议吗?
答案 0 :(得分: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'
)。
答案 1 :(得分: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) {
}
});