c# mvc 在控制器中动态解析cshtml文件并获取对应的html代码

public static string GetViewHtml(ControllerContext context, string viewName, Object param)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = context.RouteData.GetRequiredString("action");
            //context.Controller.ViewData.Model = param;
            using (var sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
                var viewContext = new ViewContext(context,
                                                  viewResult.View,
                                                  context.Controller.ViewData,
                                                  context.Controller.TempData,
                                                  sw);
                try
                {
                    viewResult.View.Render(viewContext, sw);
                }
                catch (Exception ex)
                {
                    throw;
                }

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

  

调用如下

public ActionResult  A1(){
   ViewData["a"]=1;
   retrun View();
}

public ActionResult A2(){
  ViewData["a"]=1;//这里也要有ViewData,不然报错

  var html=GetViewHtml(this.ControllerContext, "A1", null);
}

  

posted @ 2018-05-18 14:46  为乐而来  阅读(2985)  评论(0编辑  收藏  举报