ASP.NET MVC RenderPartial to String
907 ワード
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;
}