Home How to return JSON by rendering razor syntax in to string
Reply: 0

How to return JSON by rendering razor syntax in to string

user2086
1#
user2086 Published in June 22, 2018, 11:31 am

I am following the tutorial in which the instructor create a class for converting razor syntax to string which is right bellow .

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

In the controller action he return the jSON like this.

return Json(new { success = true, html = RazorViewToString.RazorToString(this,"GetAll" ,), message = "submitted succesfully" }, JsonRequestBehavior.AllowGet);

The GetALL is the action method which he passed , which is returning the list of records. which is right below.

 public ActionResult GetAll()
        {
            using (DBModel db = new DBModel())
            {
                var list = db.Employees.ToList();
                return View(list);
            }
        }

This above method is the difference I mean in that tutorial the instructor has separately created a method which is getting the list and in this action method he called that method.but in my implementation i returing the list directly as you can seen above.so in the third parameter of

RazorViewToString.RazorToString(this,"GetAll" ,)

He passed that method which i not created , what i supposed to pass here ? and also if someone can describe the functionality above i will be thankful to him. #Peace

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309828 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO