App.Web
and App.Views
are my projects in one solution, I put my views in App.Views and precompiled with RazorGenerator. It's working well if I used App.Web
like,
~/Views/Index.cshtml
is virtual path of my view in App.View
It can successfully render this view in App.Web
public ActionResult Index() {
return View("~/Views/Index.cshtml");
}
But when I try to RenderViewToString
, it returns null
.
class FakeController : ControllerBase
{
protected override void ExecuteCore() { }
public static string RenderViewToString(string controllerName, string viewName, object viewData)
{
using (var writer = new StringWriter())
{
var routeData = new RouteData();
routeData.Values.Add("controller", controllerName);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new FakeController());
var razorViewEngine = new RazorViewEngine();
var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);
var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
razorViewResult.View.Render(viewContext, writer);
return writer.ToString();
}
}
}
And this is how can all it,
FakeController.RenderViewToString("FakeName", "~/Views/Index.csthml", MessageModel);
This is discussed and probably solved in asp.net core, but I'm working with asp.net mvc 5.
Could you please help me to figure out, why it's not working?