1

设置: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);
        }
    });

我正在考虑可能为软验证错误返回不同的状态代码,但这感觉很糟糕。

4

2 回答 2

3

您可以在响应中再传递一个变量,并通过 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);

    }
于 2012-07-16T08:29:29.570 回答
1

您可以执行以下操作。

看法

 $.get("Home/Index", { random: '@DateTime.Now.Ticks' }, function (response,textData,jqXHR) {
    // Based on **jqXHR.status** value you can fill value of div
    $("#DivName").html(response);
 });

控制器

public ActionResult Index(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  
    }
}
于 2012-07-03T12:42:09.067 回答