返回一个视图作为JSON对象的一部分 [英] Returning a view as part of a JSON object

查看:323
本文介绍了返回一个视图作为JSON对象的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,只有永远载入全景一次。我这样做的原因是不重要的。最重要的是,内容的其余部分只有永远会回来的部分景色。除了一些内容我有一些JSON对象,我想来回传递,并从服务器与每个AJAX请求。

I have an app that only ever loads a full view one time. My reason for doing this is not important. What is important is that the rest of the content is only ever going to come back in partial views. In addition to some content I have some JSON objects I'd like to pass back and forth to and from the server with each AJAX request.

有没有办法返回一个JSON对象,以期作为它的一个属性?这将是非常有用的,将节省带宽作为我的当前的解决方法是使2 ajax调用,一个用于JSON和一个用于局部视图,其不仅需要更多的时间和更多的带宽,但它也需要两个单独的动作的方法和一些花哨的技巧在服务器端。序列化视图成JSON对象会解决我所有的问题。

Is there a way to return a JSON object with a view as one of its properties? This would be extremely useful and would save on bandwidth as my current workaround is to make two ajax calls, one for the JSON and one for the partial view which not only takes more time and more bandwidth, but it also requires two separate action methods and some fancy tricks on the server side. Serializing a view into a JSON object would solve all my problems.

什么是做到这一点,什么缺点(如果有的话)会有做这个的最好方法是什么?

What is the best way to accomplish this and what downsides (if any) would there be to doing this?

推荐答案

以下是code一个有趣的花絮,似乎做我想做的和preserves模型,从我可以告诉约束力。

Here's an interesting tidbit of code that seems to do what I want and preserves model binding from what I can tell.

protected string RenderPartialViewToString(string viewName, object model)
{
     controller.ViewData.Model = model;

     using (StringWriter sw = new StringWriter())
     {
          ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
          ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
          viewResult.View.Render(viewContext, sw);

          return sw.GetStringBuilder().ToString();
     }
}

工程就像一个魅力。我只是利用这一点,把这个字符串作为JSON参数,然后在客户端上我读了参数,并把它在它的合适的容器内。我很高兴能有这样的工作。

Works like a charm. I just use this and pass the string as a JSON parameter and then on the client I read the parameter and drop it in it's appropriate container. I'm very excited to have this working.

这篇关于返回一个视图作为JSON对象的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆