局部视图与JSON(或两者) [英] Partial Views vs. Json (or both)

查看:141
本文介绍了局部视图与JSON(或两者)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC使用jQuery,并有大量的Ajax请求的到我的控制器。

I use ASP.NET MVC with jQuery and have a lot of Ajax requests to my controllers.

使用局部视图(用户控件),当页面加载打造intial视图。然后,如果我需要追加/根据我的Ajax请求替换数据我建立HTML从JSON响应。

Use Partial Views (usercontrols) to build the intial view when a page is loaded. Then if I need to append/replace data based on my Ajax request I build HTML from the Json response.

此方法给了我完全控制,即得。我可以从我的控制器获得额外的信息回来,如果出事了,然后显示出基于该错误消息。

This approach gives me full control, ie. I can get extra information back from my controller if something went wrong, and then show an error message based on that.

不过,最近我一直在与所有进入维护HTML结构无论是在我的部分观点,并从Json的生成HTML的部分额外的工作真的很生气了。

However, recently I've been really annoyed with all the extra work that goes into maintaining HTML structure both in my partial views and the part that generates HTML from Json.

我喜欢做一个jQuery Ajax请求,然后让控制器返回PartialView(mypartialview),然后只需使用jQuery来代替,以HTML视图。

I like to make a jQuery ajax request and then have the controller return PartialView("mypartialview") and then just use jQuery to replace to HTML in the view.

不过,这种方式我不能从控制器附加额外的数据 - 它或者任何局部视图给​​我 - 或没有。至少,这是我目前采取它。

However, this way I cannot attach extra data from the controller - it's either whatever the partial view gives me - or nothing. At least that's my current take on it.

如果一些验证在我的控制器操作的一些点不顺心,我不希望返回局部​​视图的HTML。

If some validation goes wrong at some point in my controller action I don't want to return the HTML of the partial view.

那么,你如何去有关处理这个问题的?

So how do you go about handling this issue?

感谢您的阅读。

推荐答案

根据计算器anwser我刚才所要做同样的事情。

Based on this stackoverflow anwser I have just set out to do the same thing.

首先创建控制器类的扩展方法。

First create an extension method for the controller class.

public static string RenderViewToString(this Controller controller, string viewName, object model)
{
    using (var writer = new StringWriter())
    {
         var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
         controller.ViewData.Model = model;
         var viewCxt = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer);
         viewCxt.View.Render(viewCxt, writer);
         return writer.ToString();
     }
}

然后返回在控制器的操作方法的JSON。

Then return the json in the controllers action method.

return Json(new
                            {
                                Html = this.RenderViewToString("MyView", model),
                                SomeExtraData = data
                            });

您的Ajax请求现在收到的JSON与包含在它的HTML。这种方法在返回纯HTML片段尚在测试阶段。

Your ajax requests will now receive json with the html contained in it. Still experimenting with this approach over returning plain Html fragments.

希望有所帮助。

修改更新剃刀合作

这篇关于局部视图与JSON(或两者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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