Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Anton Oosthuizen 206 posts 486 karma points
    Sep 23, 2013 @ 13:30
    Anton Oosthuizen
    0

    6.1.5 Returning Partial View as string to JSON

    Hi All

    I need some help here.

    I need to return a partial view as a string for JSON How would I go about this. Please note that my view inherits from a DynamicNode

    Code:

       public JsonResult HandleAddReview(ReviewModel Model)
        {
            DynamicNode dn = new DynamicNode(venuecontent.Id);
            return Json(new {val =   PartialView("[Members]Reviews",dn)});
        }
    
  • Alex Skrypnyk 6163 posts 24143 karma points MVP 8x admin c-trib
    Sep 23, 2013 @ 15:26
    Alex Skrypnyk
    100

    Hi Anton,

    You have to do some method which will render Partial view in string.

    return Json(new { htmlData = RenderRazorViewToString("partialView Path", model, ControllerContext, ViewData, TempData) }, JsonRequestBehavior.AllowGet);
    
    
        public static string RenderRazorViewToString(string viewName, object model, ControllerContext controllerContext, ViewDataDictionary viewData, TempDataDictionary tempData)
        {
            viewData.Model = model;
            using (var sw = new StringWriter())
            {
                var 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();
            }
        }
    

    Thanks, Alex

  • Anton Oosthuizen 206 posts 486 karma points
    Sep 25, 2013 @ 11:11
    Anton Oosthuizen
    0

    Shot Alex.

    That is exactly what I needed.

Please Sign in or register to post replies

Write your reply to:

Draft