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

前端 未结 3 511
灰色年华
灰色年华 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:06

    I was looking for a better way to do this myself because I assumed the way I was doing it was outdated. I forget where I got this and take no credit for it, but since I ended up here I figure I'll post what I use as well. Hope it helps anyone coming along looking for something newer than the answers above.

    ** NOTE This only addresses the rendering of the view to a string. The answers above address the question about putting the result into a property on a JSON object and the OP seemed pretty comfortable with that anyway.

    public string RenderViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }
    

提交回复
热议问题