首页 > 学院 > 开发设计 > 正文

C# MVC后台将PartialView文件输出为字符串

2019-11-11 06:08:48
字体:
来源:转载
供稿:网友

在后台获取PartialView生成的字符串,可以通过如下方法进行获取生成。

代码:

 public static string RenderPartialView(ControllerContext controllerContext, ViewDataDictionary viewData,            TempDataDictionary tempData, string viewName, object model)        {            if (string.IsNullOrEmpty(viewName))            {                viewName = controllerContext.RouteData.GetRequiredString("action");            }            viewData.Model = model;            using (var stringWriter = new StringWriter())            {                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);                var viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, stringWriter);                viewResult.View.Render(viewContext, stringWriter);                var result=  stringWriter.GetStringBuilder().ToString();                return result;            }        }

调用:

 public ActionResult Data(string type)        {            var model = new Model();            model.List = QueryEntry.GetHistory(type);            var viewHtml = HtmlRender.RenderPartialView(ControllerContext,ViewData, TempData, "~/Views/History/Data.cshtml", model);            return Json(new { viewHtml });        }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表