设定:
ASP.NET MVC3,jQuery,C#
有没有人有一个干净的解决方案来处理从相同操作方法返回的不同局部视图?一个用于下一个阶段,一个用于再次返回带有验证错误的视图,另一个用于显示未处理的异常。
我有一个类似的控制器方法:
public ActionResult SomeMethod(MyModel model)
{
if(_service.Validate(model))
{
if(_service.Update(model))
{
// return next view once success
return PartialView("EverythingIsGood"); // This should be pushed into #somediv
}else{
throw new HardException("Tell the client something bad has happened");
}
}
else
{
// Return the same view to highlight the validation errors
HttpContext.Response.StatusCode = 500;
return PartialView("SomeMethod", model); // This should be pushed into #anotherdiv
}
}
客户端脚本
$.ajax({
url: baseUrl + "Home/SomeMethod",
type: "GET",
success: function (data) {
$("#somediv").html(data);
},
error: function (data) {
handleError(data);
}
});
我猜我需要像softerror这样的东西:
$.ajax({
url: baseUrl + "Home/SomeMethod",
type: "GET",
success: function (data) {
$("#somediv").html(data);
},
softerror: function (data) {
$("#anotherdiv").html(data);
},
error: function (data) {
handleError(data);
}
});
我当时在考虑为软验证错误返回一个不同的状态代码,但这感觉很麻烦。
最佳答案
您可以在响应中再传递一个变量,并通过js在客户端检查其值。
像这样的东西:
控制器:
if(_service.Update(model))
{
return Json(new {
IsEverythingGood=true;
htmlToShow=PartialView("EverythingIsGood"); // This should be pushed into #somediv
});
}
...
else
{
return return Json(new {
IsEverythingGood=false;
htmlToShow=PartialView("SomeMethod", model); // This should be pushed into #anotherdiv
}
并在您的JavaScript中:
success: function (data) {
if(data.IsEverythingGood==true){
$("#somediv").html(data.htmlToShow);
}
else if(data.IsEverythingGood==false){
$("#anotherdiv").html(data.htmlToShow);
}