Sometimes when you make an Ajax call, you want to return Html. You also want to use a partial view to design the view. The following code creates a base controller that includes a method to render a view into a string with the resulting Html. You can then return the string to the front end using a Json object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyWebsite.Web.Controllers
{
public class BaseController : System.Web.Mvc.Controller
{
protected string RenderPartialViewToString()
{
return RenderPartialViewToString(null, null);
}
protected string RenderPartialViewToString(string viewName)
{
return RenderPartialViewToString(viewName, null);
}
protected string RenderPartialViewToString(object model)
{
return RenderPartialViewToString(null, model);
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = ControllerContext.RouteData.GetRequiredString("action");
}
ViewData.Model = model;
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
}