Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kgiszewski/ac1e353eb2dc30974346c80a7b1d4a6a to your computer and use it in GitHub Desktop.
Save kgiszewski/ac1e353eb2dc30974346c80a7b1d4a6a to your computer and use it in GitHub Desktop.
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;
}
}
}
@kgiszewski
Copy link
Author

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