0

I have my entire Layout as a string in my database and I want to render the layout from database to my View. for example:

 public ActionResult index()
 {
   string layout = GetLayout();

   //in below how should I render layout to view 
   return View("index", layout);
 }

I already use result = Engine.Razor.RunCompile(template, key.ToString()); to render layout but it avoids to render HTML Helpers.

2 Answers2

2

Seems like there is no inbuilt mechanism to achieve that one.Needs to have a custom solution for that one.This topic has already been discussed in this post. Dynamically Produce Razor Views at Runtime? you can refer that one.

ErGaurav
  • 81
  • 2
1

I am using below code and it is working fine for me.i am also using it in Web API for returning View in form of string.

For more you can create Static Class and make below method static.

 public string RenderPartialView(string controllerName, string viewName, object model = null) {
     System.Web.HttpContextBase contextBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);

     var routeData = new RouteData();
     routeData.Values.Add("controller", controllerName);
     var controllerContext = new System.Web.Mvc.ControllerContext(contextBase, routeData,
      new EmptyController());

     var razorViewEngine = new System.Web.Mvc.RazorViewEngine();
     var razorViewResult = razorViewEngine.FindPartialView(controllerContext, viewName, false);

     var writer = new StringWriter();
     System.Web.Mvc.ViewContext viewContext;


     viewContext = new System.Web.Mvc.ViewContext(controllerContext, razorViewResult.View,
      new System.Web.Mvc.ViewDataDictionary(model), new System.Web.Mvc.TempDataDictionary(), writer);

     viewContext.ViewData["controller"] = controllerName;

     HttpContext.Current.Items.Add("controller", controllerName);

     razorViewResult.View.Render(viewContext, writer);

     string htmlString = writer.ToString();
     writer.Dispose();

     return htmlString;
    }

private class EmptyController: System.Web.Mvc.ControllerBase {
  protected override void ExecuteCore() {}
 }

Now please find example how we can call it from controller.

RenderPartialView("Home", string.Format("~/Views/Home/{0}.cshtml", "Index"));

I hope this will be useful to you.

Ankit Mori
  • 705
  • 14
  • 23