0

how to render partial views to strings within controllers when using razor view engine with mvc4

With webView (Aspx) i used :

public static string RenderPartialView(this Controller controller, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

            controller.ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                ViewEngineResult 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);

                return sw.GetStringBuilder().ToString();
            }
        }

I tried that solution with razor , but it can't resolve the view, Error Message :

The View can't be null => ViewResult.View

Kevorkian
  • 430
  • 2
  • 4
  • 14

1 Answers1

-1

The call to FindPartialView will not throw an exception if viewName cannot be found but the viewResult.View property will be null.

Also, when the view cannot be found, the viewResult.SearchedLocations will contain the list of locations where the view was searched. This will show you where your view was searched for.

So, given that there's not much information in your original question (and I can't comment with extra questions), my best bet would be that the viewName you're passing in cannot be found by any of the view engines.

Andrei Olariu
  • 556
  • 4
  • 8