Return Razor partial view using JSON (ASP MVC 3)

前端 未结 2 1740
清酒与你
清酒与你 2021-01-01 03:29

In MVC 2 with the regular view engine i could return a ascx partial view as string through return Json()

But with the new Razor .cshtml views I can not

相关标签:
2条回答
  • 2021-01-01 03:41

    This is the MVC 3 Beta version of the code:

        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;
        }
    
    0 讨论(0)
  • 2021-01-01 03:42

    This might help you as I've written it off the top of my head without testing it other than to validate it returns the rendered cshtml file.

    I assumed this was a method in a 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;
    }
    
    0 讨论(0)
提交回复
热议问题