MVC4 RenderViewToString Does Not Respect Mobile Views

I am creating mobile views for an asp.net MVC4 site and am facing a problem. We have quite a few places where we have a method for converting a view into a string, but this method does not seem to work with displaymodes, so it always finds the default view. For instance. index.cshtml instead of index.mobile.cshtml.

Any ideas on what's missing to make this code match mobile display modes?

public string RenderViewToString(string viewName, object model) { ViewData.Model = model; using (var sw = new StringWriter()) { var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName); if (viewResult.View == null) { var message = String.Format("View '{0}' not found. Searched in the following locations {1}.", viewName, String.Join(", ", viewResult.SearchedLocations)); throw new Exception(message); } var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View); return stripWhitespaceRx.Replace(sw.GetStringBuilder().ToString(), " ").Trim(); } } 
+5
source share
1 answer

Initialize the "viewName" parameter with the expected view.

For example, before calling RenderViewToString, specify the USER AGENT agent of the RequestName of the Request object.

 if(Request.Browser.IsMobileDevice) { viewName = "~/Views/index.mobile.cshtml"; } else { viewName = "~/Views/index.cshtml"; } 
0
source

All Articles