MVC获得某个View 或者 PartialView 生成的字符串

在开发中有时要在后台获得某个View 或者 PartialView 生成的字符串,只要你熟悉Asp.Net MVC  生命周期就能理解和敲出下面的代码。没什么高深的,直接上代码:

 

1,输出View HTML 字符串:
 

        /// <summary>
        /// 描述:输出View HTML 字符串
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="viewName">视图文件名</param>
        /// <param name="masterName">母板页文件名</param>
        /// <returns></returns>
        protected static string RenderViewToString(Controller controller, string viewName, string masterName)
        {
            IView view = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName).View;
            using (StringWriter writer = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, writer);
                viewContext.View.Render(viewContext, writer);
                return writer.ToString();
            }
        }

 

2,输出PartialView HTML 字符串:

 

        /// <summary>
        /// 描述:输出PartialView HTML 字符串
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="partialViewName">部分视图文件名</param>
        /// <returns></returns>
        protected static string RenderPartialViewToString(Controller controller, string partialViewName)
        {
            IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
            using (StringWriter writer = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, writer);
                viewContext.View.Render(viewContext, writer);
                return writer.ToString();
            }
        }

posted @ 2012-02-01 11:09  Care健康  阅读(948)  评论(2编辑  收藏  举报
版权
作者:Bober Song

出处:http://bober.cnblogs.com

Care健康:http://www.aicareyou.com

推荐空间:华夏名网

本文首发博客园,版权归作者跟博客园共有。

转载必须保留本段声明,并在页面显著位置给出本文链接,否则保留追究法律责任的权利。