使用JSON返回Razor局部视图(ASP MVC 3)

时间:2010-09-12 11:23:01

标签: asp.net-mvc razor asp.net-mvc-3

在使用常规视图引擎的MVC 2中,我可以通过return Json()

将ascx局部视图作为字符串返回

但是使用新的Razor .cshtml视图我无法弄清楚如何做到这一点。我一直在Type 'ASP.CustomerForm_cshtml' does not inherit from 'System.Web.UI.UserControl'.

部分视图继承自System.Web.Mvc.WebViewPage<T>,如果我从System.Web.UI.UserControl<T>继承第一个错误,则会弹出另一个错误。

有关如何使用ASP MVC 3和Razor视图引擎修复此问题的想法吗?

这是我的ControlToString函数:

    private string ControlToString(string controlPath, object model)
    {
        ViewPage page = new ViewPage();
        ViewUserControl ctl = (ViewUserControl)page.LoadControl(controlPath);
        page.Controls.Add(ctl);
        page.ViewData.Model = model;
        page.ViewContext = new ViewContext();
        System.IO.StringWriter writer = new System.IO.StringWriter();
        System.Web.HttpContext.Current.Server.Execute(page, writer, false);
        string outputToReturn = writer.ToString();
        writer.Close();
        //return this.Json(outputToReturn.Trim());
        return outputToReturn.Trim();
    }

2 个答案:

答案 0 :(得分:6)

这个可能会帮助你,因为我已经把它写在了我的头顶而没有测试它,除了验证它返回渲染的cshtml文件。

我认为这是Controller中的一种方法。

private string ControlToString(string controlPath, object model) {
    CshtmlView control = new CshtmlView(controlPath);

    HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter());
    control.Render(new ViewContext(this.ControllerContext, control, this.ViewData, this.TempData, writer), writer);

    string value = ((StringWriter)writer.InnerWriter).ToString();

    return value;
}

答案 1 :(得分:5)

这是代码的MVC 3 Beta版本:

    private string ControlToString(string controlPath, object model)
    {
        //CshtmlView control = new CshtmlView(controlPath);
        RazorView control = new RazorView(this.ControllerContext, controlPath, null, false, null);

        this.ViewData.Model = model;

        HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter());
        control.Render(new ViewContext(this.ControllerContext, control, this.ViewData, this.TempData, writer), writer);

        string value = ((StringWriter)writer.InnerWriter).ToString();

        return value;
    }