首页 > 代码库 > ASP.NET MVC中 在controller 里将 Partial View 转化为字符串的方法

ASP.NET MVC中 在controller 里将 Partial View 转化为字符串的方法

namespace Common.Helper{    public static class ControllerExtension    {        //根据部分视图名称,把部分视图内容转换成字符串        public static string RenderPartialViewToString(this Controller controller, string partialViewName)        {            return controller.RenderPartialViewToString(partialViewName, null);        }        //根据部分视图名称和model,把部分视图内容转换成字符串        public static string RenderPartialViewToString(this Controller controller, string partialViewName, object model)        {            //如果partialViewName为空,就把action名称作为部分视图名称            if (string.IsNullOrEmpty(partialViewName))            {                partialViewName = controller.ControllerContext.RouteData.GetRequiredString("action");            }            //把model放到Controller.ViewData.Model属性中            controller.ViewData.Model = model;            using (var sw = new StringWriter())            {                //通过视图引擎,在当前ControllerContext中,根据部分视图名称获取ViewEngineResult类型                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName);                //创建ViewContext                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData,                    controller.TempData, sw);                //把内容写到StringWriter中                viewResult.View.Render(viewContext, sw);                //StringWriter→string                return sw.GetStringBuilder().ToString();            }        }    }}