Returning a rendered HTML partial in a JSON Property in ASP.NET MVC

前端 未结 3 509
灰色年华
灰色年华 2020-12-18 10:39

I\'ve been happily returning JsonResult objects or partial ASP.NET views from my controllers in ASP.NET.

I would like to return a rendered partial view as a property

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 11:00

    Here is some code that will work cause I needed to do this today. The original code is described here.

    public static string RenderPartialToString(string controlName, object viewData)
    {
        var viewContext = new ViewContext();
        var urlHelper = new UrlHelper(viewContext.RequestContext);
        var viewDataDictionary = new ViewDataDictionary(viewData);
    
        var viewPage = new ViewPage
        {
            ViewData = viewDataDictionary,
            ViewContext = viewContext,
            Url = urlHelper
        };
    
        var control = viewPage.LoadControl(controlName);
        viewPage.Controls.Add(control);
    
        var sb = new StringBuilder();
        using (var sw = new StringWriter(sb))
        using (var tw = new HtmlTextWriter(sw))
        {
                viewPage.RenderControl(tw);
        }
    
        return sb.ToString();
    }
    

    You can then use it to do RJS style json results

    public virtual ActionResult Index()
    {
        var jsonResult = new JsonResult
        {
            Data = new
            {
                main_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()),
                secondary_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()),
            }
        };
    
        return Json(jsonResult, JsonRequestBehavior.AllowGet);
    }
    

    And the partial has a strongly typed view model

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    

    My Partial

提交回复
热议问题