Skip to content

Instantly share code, notes, and snippets.

@gillissm
Last active September 20, 2019 13:12
Show Gist options
  • Save gillissm/73310d00717d4b1276c99f7cf9a5704d to your computer and use it in GitHub Desktop.
Save gillissm/73310d00717d4b1276c99f7cf9a5704d to your computer and use it in GitHub Desktop.
MVC Controller Extension Method that allos for rendering a view to a string for usage in AJAX scenarios.
using System.IO;
using System.Web.Mvc;
namespace TheCodeAttic.Foundation.Extensions
{
public static class RenderingExtensions
{
public static string RenderViewToString<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
{
var controllerContext = controller.ControllerContext;
controllerContext.Controller.ViewData.Model = model;
// To be or not to be (partial)
var viewResult = partial ? ViewEngines.Engines.FindPartialView(controllerContext, viewName) : ViewEngines.Engines.FindView(controllerContext, viewName, null);
StringWriter stringWriter;
using (stringWriter = new StringWriter())
{
var viewContext = new ViewContext(
controllerContext,
viewResult.View,
controllerContext.Controller.ViewData,
controllerContext.Controller.TempData,
stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
}
return stringWriter.ToString();
}
}
}
[HttpPost]
public JsonResult PerformLocationSearch()
{
var searchParams = new LocationSearchParameters();
if (searchParams.SearchParamsExist)
{
int totalResult = 0;
var searchResults = _locationSearchHelper.PerformLocationSearch(searchParams, out totalResult).ToList();
if (searchResults != null && searchResults.Any())
{
var htmlstring = this.RenderViewToString("~/Views/LocationSearch/_LocationSearchResults.cshtml", searchResults, true);
return Json(new { resultCode = true,
html = htmlstring,
totalresults = totalResult,
currentpage = searchParams.RequestedPage,
msg = $"search has occurred, total results: {totalResult}" }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { resultCode = false, msg = "no results found", html = "<h3>No Results</h3>" }, JsonRequestBehavior.AllowGet);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment