Reputation: 958
In MVC5 it was possible to share Views (Razor) between projects by using a tool like Razor Generator ( http://razorgenerator.codeplex.com ).
How to achieve the same in vNext? My Views aren't recognized out of the box (the project containing views is listed as a dependency in project.json
).
InvalidOperationException: The partial view '~/Views/Authentication/_LogInForm.cshtml' was not found. The following locations were searched:
~/Views/Authentication/_LogInForm.cshtml
Upvotes: 4
Views: 2004
Reputation: 958
We finally managed to solve this. Not quite easy though...
You need to embed the views as resources in the project you'll depend on. To do this, add "resources": [ "**/*.cshtml" ]
to its project.json.
You need to create an IFileSystem that looks into those resources instead of looking on the disk. This is the tricky part. I put this on pastbin for lisibility: http://pastebin.com/aNfq5hNi
You need to register this IFileSystem in your Startup.cs:
//...
public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerfactory)
{
//Enable use of views in other assemblies
IOptions<RazorViewEngineOptions> razorViewEngineOptions=app.ApplicationServices.GetService<IOptions<RazorViewEngineOptions>>();
razorViewEngineOptions.Options.FileSystem=new MVCAsset.EmbeddedExpiringFileInfoCache(
razorViewEngineOptions,
app.ApplicationServices.GetService<ILibraryManager>()
);
//...
}
//...
NB : This is actually tested and working for MVC6 RC1, I didn't test for BETA1.
Upvotes: 3
Reputation: 1963
I'm not sure if this helps accessing views in external assemblies, but to add locations where views can be discovered you can implement IViewLocationExpander like this:
public class ViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
var locations = new List<string>(viewLocations);
locations.Add("Views/MyOtherViewLocation/{0}.cshtml");
return locations;
}
public void PopulateValues(ViewLocationExpanderContext context)
{
}
}
In your Startup.cs ConfigureServices method, add:
services.Configure<RazorViewEngineOptions>(options =>
{
var expander = new ViewLocationExpander();
options.ViewLocationExpanders.Add(expander);
});
Upvotes: 2