I have got Null reference exception when I try render razor view.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.WebPages.Scope.AspNetRequestScopeStorageProvider.get_RequestScopeInternal()
at System.Web.WebPages.Scope.AspNetRequestScopeStorageProvider.get_CurrentScope()
at System.Web.WebPages.Scope.ScopeStorage.get_CurrentScope()
at System.Web.Mvc.PreApplicationStartCode.<Start>b__0()
at System.Web.Mvc.ViewContext.get_Scope()
at System.Web.Mvc.ViewContext.get_UnobtrusiveJavaScriptEnabled()
at System.Web.Mvc.HtmlHelper.GetUnobtrusiveValidationAttributes(String name, ModelMetadata metadata)
I have found the same problem , but not found the fix.
Here is code of render:
public string RenderView(string nameFile, object model)
{
var viewData = new ViewDataDictionary
{
Model = model
};
var url = HttpContext.Current != null ? HttpContext.Current.Request.Url.ToString() : "http://localhost";
var controllerContext = new ControllerContext
{
HttpContext = new HttpContextWrapper(new HttpContext(new HttpRequest(null, url, null), new HttpResponse(null))),
RouteData = new RouteData()
{
Values = { { "controller", "empty" }, { "action", "empty" } },
DataTokens = { { "controller", "empty" }, { "action", "empty" } }
},
};
var page = new RazorView(controllerContext, nameFile, "", true, new[] { "cshtml" });
var stringBuilder = new System.Text.StringBuilder();
using (var writer = new StringWriter(stringBuilder))
{
view.Render(new ViewContext(controllerContext, page, viewData, new TempDataDictionary(), writer), writer);
return stringBuilder.ToString();
}
}
I understand that rendering outside ASP.NET Pages is not create ScopeStorage, but I can't create it manually and can't skip calling it.