The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ViewExtensions.cs 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. using System.Web.Mvc;
  9. using System.Web.UI;
  10. namespace Teknik.Utilities
  11. {
  12. public static class ViewExtensions
  13. {
  14. public static string RenderToString(this PartialViewResult partialView)
  15. {
  16. var httpContext = HttpContext.Current;
  17. if (httpContext == null)
  18. {
  19. throw new NotSupportedException("An HTTP context is required to render the partial view to a string");
  20. }
  21. var controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
  22. var controller = (ControllerBase)ControllerBuilder.Current.GetControllerFactory().CreateController(httpContext.Request.RequestContext, controllerName);
  23. var controllerContext = new ControllerContext(httpContext.Request.RequestContext, controller);
  24. var view = ViewEngines.Engines.FindPartialView(controllerContext, partialView.ViewName).View;
  25. var sb = new StringBuilder();
  26. using (var sw = new StringWriter(sb))
  27. {
  28. using (var tw = new HtmlTextWriter(sw))
  29. {
  30. view.Render(new ViewContext(controllerContext, view, partialView.ViewData, partialView.TempData, tw), tw);
  31. }
  32. }
  33. return sb.ToString();
  34. }
  35. }
  36. }