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); }