入门HTML在MVC3视图渲染 [英] Getting HTML Rendered by a View in MVC3

查看:169
本文介绍了入门HTML在MVC3视图渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我MVC3应用程序,我通过创建一个新的控制器和调用像方法指数()测试的东西,和存储所产生的的ViewResult 插入一个名为变量结果

In my MVC3 app, I'm testing stuff by creating a new controller and invoking methods like Index(), and storing the resulting ViewResult into a variable called result.

我怎么能捅这个对象(或别的东西),以获得实际的HTML返回给浏览器?

How can I poke this object (or something else) to get the actual HTML returned to the browser?

我很惊讶的是, result.ViewName 为空, result.Model 为空, result.View 为空,甚至 result.TempData 是空的。 ( result.ViewBag 拥有的东西,我把在viewbag,所以我知道整个堆栈是否正常工作。)

I am surprised that result.ViewName is empty, result.Model is null, result.View is null, and even result.TempData is empty. (result.ViewBag has stuff I put in the viewbag, so I know the whole stack is working properly.)

如果它的事项,我使用的是Visual Studio的测试,与NHibernate / ActiveRecord的沿着我的筹码。但是,所有这一切都在我的测试项目初始化正确。 (我可以从实体/对象的数据。)

If it matters, I'm using the Visual Studio testing, along with NHibernate/ActiveRecord for my stack. But all that is initializing correctly in my test project. (I can get data from entities/objects.)

推荐答案

这是我用它来创建HTML格式的电子邮件的东西,但也可能在你的情况下使用为好,视图结果的HTML输出为一个字符串。

This is something that I use to create HTML emails, but could possibly be used in your case as well, outputs the HTML of a view result into a string.

public static string RenderViewToString(Controller controller, string viewName, object model)
{
    controller.ViewData.Model = model;
    try
    {
        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null);
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);

            return sw.ToString();
        }
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

这篇关于入门HTML在MVC3视图渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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