Posted By

nivlam on 02/11/11


Tagged


Versions (?)

Use ASCX controls in MVC


 / Published in: C#
 

  1. public static class UserControlHelper
  2. {
  3. public static HtmlString RenderControl<T>(this HtmlHelper helper, string controlPath)
  4. where T : UserControl
  5. {
  6. return RenderControl<T>(helper, controlPath, null);
  7. }
  8.  
  9. public static HtmlString RenderControl<T>(this HtmlHelper helper, string controlPath, Action<T> action)
  10. where T : UserControl
  11. {
  12. Page pageHolder = new Page();
  13. T controlToRender = (T)pageHolder.LoadControl(controlPath);
  14. pageHolder.Controls.Add(controlToRender);
  15.  
  16. if (action != null)
  17. action(controlToRender);
  18.  
  19. using (StringWriter sw = new StringWriter())
  20. {
  21. HttpContext.Current.Server.Execute(pageHolder, sw, false);
  22. return new HtmlString(sw.ToString());
  23. }
  24. }
  25. }

Report this snippet  

You need to login to post a comment.