I am using the solution which returns the Html in the json object. If there are any problems with doing that please let me know. Here is how I went about it.
Controller extension to render partial a view (included but not used in this solution is RenderViewToString). This can be found in various forms across different answers which did not seem to match my customized version which I do not take credit for.
namespace System.Web.Mvc
{
using System.IO;
public static class MvcControllerExtension
{
public static string RenderPartialViewToString(this Controller controller, string viewName = null, object model = null)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
}
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public static string RenderViewToString(this Controller controller, string viewName = null, object model = null, string masterName = null)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
}
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
}
In the controller action returning JsonResult
public JsonResult _DisplayByFoo(int catId)
{
var myRealModel = new MyRealModel(catId);
// .... omitted the construction of MyRealModel
var jsonModel = new JsonModel(myRealModel);
jsonModel.Html = this.RenderPartialViewToString("_Display", myRealModel);
return Json(jsonModel);
}
I also include other properties on the json object which help me determine my insertion mode.
In Js; after my AjaxCall to the Json action. Run OnSuccess method, which, apart from other logic, does the following.
$("#" + targetId).append(MyJson.Html);
JQuery.load. otherwise use a JQuery Ajax call