2

How do you render a view as a string from a controller in MVC 2?

In MVC 1, I used CaptureActionHtml. I'm having the same problem with it as a similar question, but is there a way to do this without Rhink.Mocks?

3
  • IMHO: You shouldn't. You should do this in an ActionResult, not in a Controller. What are you trying to do? Commented Apr 30, 2010 at 17:22
  • What's the difference? Isn't an ActionResult in the Controller? I'm trying to use the view as template for an email. Commented Apr 30, 2010 at 17:45
  • 1
    No, Controllers and ActionResults are two different types. Controllers instantiate ActionResults; Controllers don't implement ActionResults Controllers shouldn't know about HTML at all. Here's the general idea: aboutcode.net/2009/01/19/EmailActionResultInASPNETMVC.aspx Commented Apr 30, 2010 at 21:38

1 Answer 1

0

I've found Steve Sanderson's Integration Testing framework to work out very well for this.

Perusing one of the code samples from his own blog post gives you some idea of the capabilities of the framework, the assertions that you can perform against its output, etc:

[Test]
public void Root_Url_Renders_Index_View()
{
    appHost.SimulateBrowsingSession(browsingSession => {
        // Request the root URL
        RequestResult result = browsingSession.ProcessRequest("/");

        // You can make assertions about the ActionResult...
        var viewResult = (ViewResult) result.ActionExecutedContext.Result;
        Assert.AreEqual("Index", viewResult.ViewName);
        Assert.AreEqual("Welcome to ASP.NET MVC!", viewResult.ViewData["Message"]);

        // ... or you can make assertions about the rendered HTML
        Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.