2
我想呈現從服務器端事件(無請求)的部分視圖。假的HttpContext? (ASP.NET MVC)
我發現了下面的代碼,它能夠在沒有控制器的情況下渲染部分視圖。 Render MVC PartialView into SignalR response
public static string RenderPartialView(string controllerName, string partialView, object model)
{
var context = new HttpContextWrapper(System.Web.HttpContext.Current) as HttpContextBase;
var routes = new System.Web.Routing.RouteData();
routes.Values.Add("controller", controllerName);
var requestContext = new RequestContext(context, routes);
string requiredString = requestContext.RouteData.GetRequiredString("controller");
var controllerFactory = ControllerBuilder.Current.GetControllerFactory();
var controller = controllerFactory.CreateController(requestContext, requiredString) as ControllerBase;
controller.ControllerContext = new ControllerContext(context, routes, controller);
var ViewData = new ViewDataDictionary();
var TempData = new TempDataDictionary();
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialView);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
的客戶端請求(SignalR/WebSocket的)後使用時,也能正常工作,但如果代碼是由一個服務器端事件(WCF連接到其他應用),HttpContext.Current = NULL觸發這導致錯誤。
我該如何做這項工作?
PS。我也嘗試過Razor引擎,但是我收到錯誤「無法編譯模板,名稱'Html'在當前上下文中不存在」。由於該模板還包含「@Html」,因此剃刀引擎似乎無法在控制器外部解析模板。