Tuesday, 9 April 2019

Render partial view at server side and set to view dynamically

Well this is a situation where the .net framework come into picture.
There is a condition where you have to return a data object as well as a partial view in any of your action method in controller.
Do like this - 

public string RenderPartialView(string viewName, object model)
        {
            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(); // this line return exactly the html of partial view with data
            }
        }
public ActionResult Create(ProductModel model, int type)
        {
            string msg = "";  
            msg = GetUIMessageString(type);
            return Json(new { msg, table = RenderPartialView("_ProductList", model) }); // returns a json to view and partial view as html string     
        }

Note:  Try to place the RenderPartialView() method in a class where all your controllers can access it like -  in a parent class.

1 comment:

Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...