在MVC3剃须刀,我怎么一个动作内部渲染视图的HTML? [英] In MVC3 Razor, how do I get the html of a rendered view inside an action?

查看:108
本文介绍了在MVC3剃须刀,我怎么一个动作内部渲染视图的HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人知道如何获得一个动作内部的视图的生成html?

它是这样的:

 公众的ActionResult DO()
{
    VAR HTML =的RenderView(你好,模型);
...
}


解决方案

我在使用I类名为 Utilities.Common 我的意见传递给客户端的静态方法作为JSON的属性的对象不断让我有必要给他们呈现为一个字符串。这里亚去:

 公共静态字符串RenderPartialViewToString(控制器控制器,字符串的viewName,对象模型)
{
    controller.ViewData.Model =模型;
    使用(StringWriter的SW =新的StringWriter())
    {
        ViewEngineResult的ViewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext,的viewName);
        ViewContext viewContext =新ViewContext(controller.ControllerContext,viewResult.View,controller.ViewData,controller.TempData,SW);
        viewResult.View.Render(viewContext,SW);        返回sw.ToString();
    }
}

这将为全面的意见,以及局部视图的工作,只是改变 ViewEngines.Engines.FindPartialView ViewEngines.Engines.FindView

Does anybody know how to get the generated html of a view inside an action?

Is it something like this:

public ActionResult Do()
{
    var html = RenderView("hello", model);
...
}

解决方案

I use a static method in a class I called Utilities.Common I pass views back to the client as properties of JSON objects constantly so I had a need to render them to a string. Here ya go:

public static string RenderPartialViewToString(Controller controller, 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.ToString();
    }
}

This will work for full views as well as partial views, just change ViewEngines.Engines.FindPartialView to ViewEngines.Engines.FindView.

这篇关于在MVC3剃须刀,我怎么一个动作内部渲染视图的HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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