MVC控制器中使用Razor解析出Html字符串的扩展方法

时间:2020-12-15 作者:WilliamChan

在写MVC控制器Action方法的时候,经常需要组合输出几个视图页面的内容,一次性发给前端,但是直接用一个View是不好实现的。这里给MVC控制器加个扩展方法,使用Razor来解析出Html字符串,以且实现前面的需求。

public static class ControllerExtension
{
      /// <summary>
      /// Renders a (partial) view to string.
      /// </summary>
      /// <param name="controller">Controller to extend</param>
      /// <param name="viewName">(Partial) view to render</param>
      /// <returns>Rendered (partial) view as string</returns>
      public static string RenderPartialViewToString(this ControllerBase controller, string viewName)
      {
          return controller.RenderPartialViewToString(viewName, null);
      }

      /// <summary>
      /// Renders a (partial) view to string.
      /// </summary>
      /// <param name="controller">Controller to extend</param>
      /// <param name="viewName">(Partial) view to render</param>
      /// <param name="model">Model</param>
      /// <returns>Rendered (partial) view as string</returns>
      public static string RenderPartialViewToString(this ControllerBase controller, string viewName, object model)
      {
          if (string.IsNullOrEmpty(viewName))
              viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

          controller.ViewData.Model = model;

          using (var sw = new StringWriter())
          {
              var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
              var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
              viewResult.View.Render(viewContext, sw);

              return sw.GetStringBuilder().ToString();
          }
      }
}

像这样来用

return Json(new
           {
               Success = true,
               Message = "Sucess",
               Html1 = this.RenderPartialViewToString("_Html1", model1),
               Html2 = this.RenderPartialViewToString("_Html2", model2)
           }, JsonRequestBehavior.AllowGet);

以上就是知道不介绍的《MVC控制器中使用Razor解析出Html字符串的扩展方法》,希望对你有所帮助。

声明:若您对本文内容有任何意见,欢迎发送邮件至:admin@zhidaobu.com,本站会尽快回应并做出相应处理。