Reputation: 447
I am using Razor outside MVC. I would like to render view as string. Here is my method:
public async Task<string> RenderToStringAsync(string viewName, object model)
{
var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
using (var sw = new StringWriter())
{
var viewResult = _viewEngine.FindView(actionContext, viewName, false);
if (viewResult.View == null)
{
throw new ArgumentNullException($"{viewName} does not match any available view");
}
var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};
var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
sw,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return sw.ToString();
}
}
I've created Views folder and pasted there few views. All the files has Copy to Output Directory - Copy always. But I am getting next here
var viewResult = _viewEngine.FindView(actionContext, viewName, false);
viewResult has property Success which is always false and also has property SearchedLocations with values: "/Views/Shared/Email.cshtml" and "/Views//Email.cshtml". Any ideas ?
Upvotes: 0
Views: 1561
Reputation: 65
Default view locations are /Views/{1}/{0}.cshtml
and /Views/Shared/{0}.cshtml
Probably the controller doesn't exist (and razor can't find controller), so it's /Views//Email.cshtml
in your case.
You can add custom location by adding a new view location expander:
public class ViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
var locationWithoutController = "/Views/{0}.cshtml";
return viewLocations.Union(new[] { locationWithoutController });
}
public void PopulateValues(ViewLocationExpanderContext context)
{
}
}
Register you expander in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddRazorOptions(options =>
{
options.ViewLocationExpanders.Add(new ViewLocationExpander());
});
}
Upvotes: 1