2010-04-10 52 views
0

我想知道是否可以将视图作为JSON对象返回。在我的控制器我想要做的东西像下面这样:可以将一个视图作为ASP.Net中的JSON对象返回MVC

 [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

我真的不推荐这种方法 - 如果您想确保调用成功,请使用协议中和jQuery库中内置的HTTPHeader。如果你看看$.ajax的API文档,你会发现你可以对不同的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"); 
} 

但是,是的,这是可以做到的方式太。您的方法存在的问题是您要返回PartialView本身,而不是输出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() }); 
} 
+0

感谢托马斯 - 我很欣赏的指针再度最佳实践,但我不是在看200或500错误。这更适合验证我返回成功的位置,然后返回相关的局部视图。有成功和失败的观点,但是我仍然需要在返回结果后在页面的其他地方做一些处理。我尽可能简单地举例说明技术答案,而不是设计方案。再次感谢你的回复! – Chev 2010-04-11 06:48:20

+0

托马斯 - 使用mvc 1.0我没有访问ControllerContext.ParentActionViewContext属性? – Chev 2010-04-11 10:57:40

+0

嗯......我所展示的代码显然来自于.NET 4的MVC 2,因为这正是我正在使用的。我将在MVC 1中查看一些方法 - 但我的搜索算法将是“ah,intellisense - 嗯,这是什么?”,所以你可以尽可能地发现它:P – 2010-04-11 11:45:36

0

你为什么要返回封装在JSON对象中的视图? 它可能会工作,但它是下一个开发人员说“WTF?!?”的开放门户。

为什么不只是让你的行动回报PartialView调用$获得()和注射,或甚至更优质的通话

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

编辑:

好吧,既然你要发送的值,你可以使用获取或加载,显然,但你的方法仍然没有多大意义... 我想你会应用一些变化取决于你的json对象中的成功变量,你的回报。但是,您最好在服务器端保留这种逻辑,并根据您的条件返回一个视图或另一个视图。例如,您可以返回一个JavascriptRersult,例如一旦它被检索到就会执行一段JavaScript ...或返回2个不同的PartialViews。

+0

感谢您的答复斯蒂芬 - 请我评论托马斯的后上方 – Chev 2010-04-11 06:50:12

相关问题