在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
在开发中有时要在后台获得某个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(); } }
原文地址:http://www.cnblogs.com/xumingxiang/archive/2012/01/14/2322567.htm 作者 : 徐明祥 出处:http://www.cnblogs.com/xumingxiang 版权:本文版权归作者和博客园共有 转载:欢迎转载,为了保存作者的创作热情,请按要求【转载】,谢谢 要求:未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
|
请发表评论