我正在制作一个 jQuery JSON 帖子,并希望将 PartialView 作为 HTML 返回。在我的控制器中,我需要将 PartialView 制作成 HTML。
我找到了一些示例,但其中大多数都涉及 BaseController。我的项目不允许我使用 BaseController。我宁愿需要一个可以在控制器中使用的扩展。
我查看了一些代码并找到了一个示例,但我在使用它时遇到了一些问题。我不知道如何传入我使用的当前控制器。
[HttpPost]
public ActionResult HtmlJsonTryout(/*passing values*/)
{
//code here......
if (first.CartID == 0)
{
var viewData = m_cartViewDataFactory.Create();
var miniCart = ControllerExtensionsHelper.PartialViewToString("HERE I NEED TO PASS CONTROLLER RIGHT?", "_FullCart", viewData);
var cart = PartialView("_CartSum", viewData);
this.Response.ContentType = "application/json";
return Json(new
{
Status = "OK",
MiniCart = miniCart,
Cart = cart
});
}
}
public static class ControllerExtensionsHelper
{
public static string PartialViewToString(this Controller controller)
{
return controller.PartialViewToString(null, null);
}
public static string RenderPartialViewToString(this Controller controller, string viewName)
{
return controller.PartialViewToString(viewName, null);
}
public static string RenderPartialViewToString(this Controller controller, object model)
{
return controller.PartialViewToString(null, model);
}
public static string PartialViewToString(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
{
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
}
controller.ViewData.Model = model;
using (StringWriter stringWriter = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
return stringWriter.GetStringBuilder().ToString();
}
}
}