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

Mar*_*tin 5 asp.net-mvc razor asp.net-mvc-3

在具有常规视图引擎的MVC 2中,我可以将ascx局部视图作为字符串直通返回 return Json()

但是使用新的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();
    }
Run Code Online (Sandbox Code Playgroud)

Bui*_*ted 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;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*tin 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;
    }
Run Code Online (Sandbox Code Playgroud)