public static class ContollerExtensions { public static ViewFormatResult ViewFormat(this Controller controller) { return ViewFormat(controller,null /* viewName */, null /* masterName */, null /* model */); } public static ViewFormatResult ViewFormat(this Controller controller,object model) { return ViewFormat(controller, null /* viewName */, null /* masterName */, model); } public static ViewFormatResult ViewFormat(this Controller controller, string viewName) { return ViewFormat(controller, viewName, null /* masterName */, null /* model */); } public static ViewFormatResult ViewFormat(this Controller controller, string viewName, string masterName, object model) { if (model != null) { controller.ViewData.Model = model; } return new ViewFormatResult { ViewName = viewName, MasterName = masterName, ViewData = controller.ViewData, TempData = controller.TempData }; }
public class ViewFormatResult : ViewFormatResultBase { private string _masterName; public string MasterName { get { return _masterName ?? String.Empty; } set { _masterName = value; } } protected override ViewEngineResult FindView(ControllerContext context) { ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName); if (result.View != null) { return result; } // we need to generate an exception containing all the locations we searched StringBuilder locationsText = new StringBuilder(); foreach (string location in result.SearchedLocations) { locationsText.AppendLine(); locationsText.Append(location); } throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "{0}{1}", ViewName, locationsText)); }
public abstract class ViewFormatResultBase : ViewResultBase { public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (String.IsNullOrEmpty(ViewName)) { ViewName = context.RouteData.GetRequiredString("action"); } ViewEngineResult result = null; if (View == null) { result = FindView(context); View = result.View; } TextWriter writer = context.HttpContext.Response.Output; ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, writer); WriterHtml(writer, viewContext); //View.Render(viewContext, writer); if (result != null) { result.ViewEngine.ReleaseView(context, View); } } public void WriterHtml(TextWriter writer, ViewContext viewContext) { StringWriter sw = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(sw); View.Render(viewContext,htmlWriter); string html = sw.ToString(); html = Regex.Replace(html, "[f v]", ""); html = Regex.Replace(html, " {2,}", " "); html = Regex.Replace(html, ">[ ]{1}", ">"); string pattern = @"//<![CDATA["; html = Regex.Replace(html, pattern, "//<![CDATA[ "); html = Regex.Replace(html, @"</head>", "</head> "); html = Regex.Replace(html, @"</body>", "</body> "); writer.Write(html); } }
最后调用
public ActionResult Index()
{
return this.ViewFormat();
}