2

我正在制作一个 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();
        }
    }
}
4

1 回答 1

2

您没有正确使用扩展方法。您在它们正在扩展的类的实例上调用扩展方法。请阅读有关扩展方法的文档:

[HttpPost]
public ActionResult HtmlJsonTryout(int amount)
{
    if (first.CartID == 0)
    {               
        var viewData = m_cartViewDataFactory.Create();
        string miniCart = this.PartialViewToString("_FullCart", viewData);
        string cart = this.PartialViewToString("_CartSum", viewData);

        return Json(new
        {
            Status = "OK",
            MiniCart = miniCart,
            Cart = cart
        });
    }
}
于 2012-05-31T07:11:35.473 回答