Render MVC PartialView into SignalR response

前端 未结 6 993
抹茶落季
抹茶落季 2020-12-13 04:19

I would like to render a PartialView to an HTML string so I can return it to a SignalR ajax request.

Something like:

SignalR Hub (mySignal

6条回答
  •  离开以前
    2020-12-13 05:02

    Here, this is what I use in Controllers for ajax, I modified it a bit so it can be called from method instead of controller, method returnView renders your view and returns HTML string so you can insert it with JS/jQuery into your page when you recive it on client side:

      public static string RenderPartialToString(string view, object model, ControllerContext Context)
            {
                if (string.IsNullOrEmpty(view))
                {
                    view = Context.RouteData.GetRequiredString("action");
                }
    
                ViewDataDictionary ViewData = new ViewDataDictionary();
    
                TempDataDictionary TempData = new TempDataDictionary();
    
                ViewData.Model = model;
    
                using (StringWriter sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(Context, view);
    
                    ViewContext viewContext = new ViewContext(Context, viewResult.View, ViewData, TempData, sw);
    
                    viewResult.View.Render(viewContext, sw);
    
                    return sw.GetStringBuilder().ToString();
                }
            }
    
            //"Error" should be name of the partial view, I was just testing with partial error view
            //You can put whichever controller you want instead of HomeController it will be the same
            //You can pass model instead of null
            private string returnView()
            {
                var controller = new HomeController();
                controller.ControllerContext = new ControllerContext(HttpContext,new System.Web.Routing.RouteData(), controller);
                return RenderPartialToString("Error", null, new ControllerContext(controller.Request.RequestContext, controller));
            }
    

    I didn't test it on a Hub but it should work.

提交回复
热议问题