Skip to content

Instantly share code, notes, and snippets.

@jcteague
Created June 2, 2010 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcteague/421943 to your computer and use it in GitHub Desktop.
Save jcteague/421943 to your computer and use it in GitHub Desktop.
public static class TestViewExtension
{
public static string RenderViewUnderTest(this HtmlHelper helper, string controller, string action, object model)
{
var ctx = new ViewDataDictionary(model);
helper.ViewContext.RouteData.Values["Controller"] = controller;
helper.ViewContext.RouteData.Values["Action"] = action;
var sw = new StringWriter();
var viewContext = new ViewContext(helper.ViewContext, helper.ViewContext.View,ctx,helper.ViewContext.TempData, sw);
var viewResult = ViewEngines.Engines.FindView(viewContext, action, string.Empty);
viewResult.View.Render(viewContext, viewContext.Writer);
sw.Close();
var sb = sw.GetStringBuilder();
var text = sb.ToString();
text = stripDocType(text);
text = stringHtmlTag(text);
text = StringBodyTag(text);
return text;
}
static string StringBodyTag(string text)
{
var body_begin = text.IndexOf("<body");
if(body_begin >=0)
{
var body_end = text.IndexOf(">", body_begin);
text = text.Remove(body_begin, body_end - body_begin + 1).Replace("</body>", "");
}
return text;
}
static string stringHtmlTag(string text)
{
var html_begin = text.IndexOf("<html");
if (html_begin >= 0)
{
var html_end = text.IndexOf(">", html_begin);
text = text.Remove(html_begin, html_end - html_begin + 1).Replace("</html>", "");
}
return text;
}
static string stripDocType(string text)
{
var doctype_begin = text.IndexOf("<!DOCTYPE");
if(doctype_begin >=0)
{
var doctype_end = text.IndexOf(">", doctype_begin);
text = text.Remove(doctype_begin, doctype_end - doctype_begin + 1);
}
return text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment