Created
June 27, 2018 13:21
-
-
Save kgiszewski/ac1e353eb2dc30974346c80a7b1d4a6a 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
using System.IO; | |
using System.Web; | |
using System.Web.Mvc; | |
using System.Web.Routing; | |
namespace MendozaDM.Core.Helpers | |
{ | |
public static class TransformationHelper | |
{ | |
/// <summary> | |
/// Renders a named razor view from a given model. | |
/// </summary> | |
/// <param name="context">The context.</param> | |
/// <param name="viewName">Name of the view.</param> | |
/// <param name="model">The model.</param> | |
/// <returns></returns> | |
public static string RenderRazorViewToString(ControllerContext context, string viewName, object model) | |
{ | |
using (var sw = new StringWriter()) | |
{ | |
var viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(context, viewName); | |
var viewContext = new ViewContext(context, viewResult.View, new ViewDataDictionary(model), new TempDataDictionary(), sw); | |
viewResult.View.Render(viewContext, sw); | |
return sw.GetStringBuilder().ToString(); | |
} | |
} | |
public static ControllerContext GetFakeControllerContext(HttpContextBase httpContextBase) | |
{ | |
var factory = DependencyResolver.Current.GetService<IControllerFactory>() ?? new DefaultControllerFactory(); | |
var controller = factory.CreateController(new RequestContext(httpContextBase, new RouteData()), "Fake") as FakeController; | |
var route = new RouteData(); | |
route.Values.Add("controller", "Fake"); | |
var newContext = new ControllerContext(new HttpContextWrapper(HttpContext.Current), route, controller); | |
controller.ControllerContext = newContext; | |
return controller.ControllerContext; | |
} | |
} | |
public class FakeController : Controller | |
{ | |
ActionResult Fake() | |
{ | |
return null; | |
} | |
} | |
} |
Need to eliminate MVC altogether? Try this: https://github.com/RickStrahl/Westwind.RazorHosting
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TransformationHelper.RenderRazorViewToString(TransformationHelper.GetFakeControllerContext(new HttpContextWrapper(HttpContext.Current)), "~/Views/Partials/myView.cshtml", myModel);