Asp.net mvc获取View生成的html
2012-05-15 14:27 watsonchia 阅读(621) 评论(4) 编辑 收藏 举报客户端获取某个view生成的最终html是很容易的,用jquery的ajax只需要一句。
$.get("/Home/Test", function (data) {
//得到view的html
});
//得到view的html
});
如果在服务端获取view生成的html,需要以下这个方法。
string ViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
此方法同样适用于PartialView,只要把FindView那句换成
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);