ASP MVC视图内容为JSON [英] ASP MVC View Content as JSON

查看:96
本文介绍了ASP MVC视图内容为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有相当正在使用Ajax(jQuery的)呼吁并返回局部视图内容的更新屏幕的一部分几个控制器操作一个MVC应用程序。但我宁愿做的是返回JSON这样的事情。

I have a MVC app with quite a few Controller Actions that are called using Ajax (jQuery) and return partial views content which updates a part of the screen. But what I would rather do is return JSON something like this.

return Json(new { 
    Result = true, 
    Message = "Item has been saved", 
    Content = View("Partial") 
});

当HTML仅仅是一个JSON的财产。这意味着我需要检索由视图方式呈现的HTML。有没有简单的方法来做到这一点,我已经看到了几个例子都相当令人费解。

Where the HTML is just a property of the Json. What this means is I need to retrieve the HTML that is rendered by the View method. Is there any easy way to do this, a few examples I have seen are quite convoluted.

编辑:这个问题最初是为ASP.NET MVC 1,但如果第2版更容易,我想听到的答案

This question was originally for ASP.NET MVC 1, but if version 2 makes it easier I would like to hear the answer.

推荐答案

下面就是答案!距离马丁从的方法略有变化,似乎工作。如果有东西遗失,请能让人有助于在评论部分的任何code的变化。谢谢你。

Here is the answer! It is slight change from Martin From's method and it seems to work. If there are things missing please can people contribute any code changes in the comments section. Thanks.

从你控制器调用它是这样的:

From you controller call it like this:

string HTMLOutput = Utils.RenderPartialToString("~/Views/Setting/IndexMain.ascx", "", items, this.ControllerContext.RequestContext);

这添加到类

public static string RenderPartialToString(string controlName, object viewData, object model, System.Web.Routing.RequestContext viewContext)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };

     vp.ViewData = vd;
     vp.ViewData.Model = model;
     vp.ViewContext = new ViewContext();
     vp.Url = new UrlHelper(viewContext);

     Control control = vp.LoadControl(controlName);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();

     using (StringWriter sw = new StringWriter(sb))
     using (HtmlTextWriter tw = new HtmlTextWriter(sw))
     {
         vp.RenderControl(tw);
     }

     return sb.ToString();
}

这篇关于ASP MVC视图内容为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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