5

在具有常规视图引擎的 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();
    }
4

2 回答 2

6

可能会对您有所帮助,因为我已经将它写在我的头上,除了验证它是否返回渲染的 cshtml 文件之外,没有对其进行测试。

我认为这是控制器中的一种方法。

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;
}
于 2010-09-12T19:54:38.747 回答
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;
    }
于 2010-10-24T16:07:57.897 回答