代码之家  ›  专栏  ›  技术社区  ›  Samuel Goldenbaum

在ASP.NETMVC中,视图能否作为JSON对象返回

  •  0
  • Samuel Goldenbaum  · 技术社区  · 16 年前

    我想知道是否可以将视图作为JSON对象返回。在控制器中,我想执行以下操作:

            [AcceptVerbs("Post")]
            public JsonResult SomeActionMethod()
            {
                return new JsonResult { Data = new { success = true, view = PartialView("MyPartialView") } };
            }
    

    在html中:

     $.post($(this).attr('action'), $(this).serialize(), function(Data) {
                            alert(Data.success);
                            $("#test").replaceWith(Data.view);
    
                        });
    

    3 回复  |  直到 16 年前
        1
  •  3
  •   Tomas Aschan    16 年前

    我真的不推荐这种方法-如果您想确保调用成功,请使用协议和jQuery库中内置的HTTPHeader。如果你看一下API文档 $.ajax 您将发现您可以对不同的HTTP状态代码有不同的反应—例如,有成功和错误回调。 使用这种方法,您的代码看起来像

    $.ajax({
        url: $(this).attr('action'),
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'HTML',
        success: function(data, textStatus, XMLHttpRequest) { 
                     alert(textStatus);
                     $('#test').html(data); 
                 },
        error: function(XmlHttpRequest, textStatus, errorThrown) {
                   // Do whatever error handling you want here.
                   // If you don't want any, the error parameter
                   //(and all others) are optional
               }
        }
    

    PartialView :

    public ActionResult ThisOrThat()
    {
        return PartialView("ThisOrThat");
    }
    

    局部视图 而不是输出HTML。如果将代码更改为:

    public ActionResult HelpSO()
    {
        // Get the IView of the PartialView object.
        var view = PartialView("ThisOrThat").View;
    
        // Initialize a StringWriter for rendering the output.
        var writer = new StringWriter();
    
        // Do the actual rendering.
        view.Render(ControllerContext.ParentActionViewContext, writer);
        // The output is now rendered to the StringWriter, and we can access it
        // as a normal string object via writer.ToString().
    
        // Note that I'm using the method Json(), rather than new JsonResult().
        // I'm not sure it matters (they should do the same thing) but it's the 
        // recommended way to return Json.
        return Json(new { success = true, Data = writer.ToString() });
    }
    
        2
  •  0
  •   Stéphane    16 年前

    它可能会工作,但这是一个开放的大门,为下一个开发商说:“WTF?!?”

    为什么不让您的操作返回PartialView调用$.get()并注入它,或者更好地调用它呢

    $("#target").load(url);
    

    编辑:

    好吧,既然您正在发布值,显然可以使用get或load,但是您的方法仍然没有多大意义。。。 我想您将根据返回的json对象中的success变量应用一些更改。但是您最好在服务器端保留这种逻辑,并根据您的条件返回一个或另一个视图。例如,您可以返回一个JavaScriptreResult,它将在检索到javascript时立即执行它。。。或者返回两个不同的partialview。

        3
  •  0
  •   Lee    16 年前

    看看这个例子 http://geekswithblogs.net/michelotti/archive/2008/06/28/mvc-json---jsonresult-and-jquery.aspx

    您应该能够返回这个.Json(obj),其中obj只是您想要序列化的数据。

    另外,如果使用类型设置为“json”的$.getJSON或$.ajax方法,则结果将自动转换为客户端上的javascript对象,这样您就可以使用数据而不是字符串。