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); }
欢迎加入JAVA技术交流QQ群:179945282
欢迎加入ASP.NET(C#)交流QQ群:17534377