代码改变世界

ASP.NET MVC RenderPartial to String

2010-09-03 10:38  敏捷的水  阅读(762)  评论(0编辑  收藏  举报

Static Method to render string

public static string RenderPartialToString(string partialFile, object viewData)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };
     Control control = vp.LoadControl(partialFile);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (HtmlTextWriter tw = new HtmlTextWriter(sw))
         {
             vp.RenderControl(tw);
         }
     }

     return sb.ToString();
}

 

// Controller Method
public string GetHtmlFromPartial()
{
     
     var viewData = new SomeViewData { Note = n };

     string s = RenderPartialToString("~/Views/Error.ascx", viewData);

     return s;
}