In MVC Project I dynamically render a view to string using the following code.
public string RenderViewToString(string viewName, object model, RequestContext requestContext){
ViewData.Model = model;
var cContext = ControllerContext;
if (cContext == null)
{
var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
var ctrl = ctrlFactory.CreateController(requestContext, "Documents") as Controller;
var newCContext = new ControllerContext(requestContext, ctrl);
cContext = newCContext;
var ctrlDesc = new ReflectedControllerDescriptor(ctrl.GetType());
}
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(cContext, viewName);
var viewContext = new ViewContext(cContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(cContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
This works fine until multiple users run the code at the same time. It then gets each users' view data mixed up.
Any suggestions why? Thanks
I had the same problem with similar code. I spend a couple of days figuring this one out. After reading loads around this, containing suggestions like 'write your own viewRenderer' and so on, it all seemed to complex to solve this problem. After diving into the .net code itself, I found a dirty trick that that fixes this
Add a couple of lines to your ConfigureServices (startup):
It makes the IViewRenderer and IViewBufferScope transient, which solves the problem. The reason the IViewBufferScope is added this way, is because it's an internal, so some trickery is needed to get to it.