Created
June 2, 2010 04:47
-
-
Save jcteague/421943 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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