8

I was reading a post by Brad Wilson (http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html) on the new ViewEngine changes to MVC Preview 5 and thought that it would be great to be able to render a view to string for use in tests. I get the impression from the article that it may be possible to achieve this but cannot figure out how.

I believe this would enable us to do away with some of our WatIn tests (which are slow and unreliable) as it would allow us to check that the View has rendered correctly by simply checking the string for expected values/text.

Has anyone implemented something like this?

Haacked
  • 58,045
  • 14
  • 90
  • 114
Chris Knight
  • 413
  • 2
  • 5
  • 14

3 Answers3

5

It's tricky. What you have to do is set the Response.Filter property to a custom stream class that you implement. The MVC Contrib project actually has examples of doing this. I'd poke around in there.

Haacked
  • 58,045
  • 14
  • 90
  • 114
1

I think here is what you need. The RenderPartialToString function will return the controller as a string. I get it from here.

public static string RenderPartialToString(string controlName, object viewData)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };
     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();
}
Community
  • 1
  • 1
Triet Doan
  • 11,455
  • 8
  • 36
  • 69
0

Moreover testing, it can be useful for components such as HTML to PDF converters. These components usually uses 2 ways of transformation.

  • Passing a URL to the conversion method
  • Passing a HTML content (and you can optionally specify the baseUrl to resolve virtual paths)

I am using an Authorize filter inside the controller, so if I redirect to the URL the rendered HTML is the login page one (I use a custom authentication).

If I use Server.Execute(Url) to keep the context, the method fails (HttpUnhandledException: Error executing child request for /Template/Pdf/1.).

So I tried to retrieve the HTML of the rendered ViewResult but I didn't succeed.

labilbe
  • 3,501
  • 2
  • 29
  • 34