Getting HTML Rendered by a View in MVC3

2019-09-06 20:37发布

问题:

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.

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

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.)

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.)

回答1:

Things to notice:
1. ViewName is empty if you just write return View(); and don't write the view name explicity.
2. TempData is property of the controller so as for ViewBag. See MSDN

Update: By the way there is a wonderfull library for testing in mvc MvcContrib



回答2:

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();
    }
}