Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the view location in asp.net core mvc when using custom locations?

Let's say I have a controller that uses attribute based routing to handle a requested url of /admin/product like so:

[Route("admin/[controller]")]         public class ProductController: Controller {      // GET: /admin/product     [Route("")]     public IActionResult Index() {          return View();     } } 

Now let's say that I'd like to keep my views organized in a folder structure that roughly reflects the url paths they are related to. So I'd like the view for this controller to be located here:

/Views/Admin/Product.cshtml 

To go further, if I had a controller like this:

[Route("admin/marketing/[controller]")]         public class PromoCodeListController: Controller {      // GET: /admin/marketing/promocodelist     [Route("")]     public IActionResult Index() {          return View();     } } 

I would like the framework to automatically look for it's view here:

Views/Admin/Marketing/PromoCodeList.cshtml 

Ideally the approach for informing the framework of the view location would work in a general fashion based on the attribute based route information regardless of how many url segments are involved (ie. how deeply nested it is).

How can I instruct the the Core MVC framework (I'm currently using RC1) to look for the controller's view in such a location?

like image 769
RonC Avatar asked Apr 20 '16 14:04

RonC


People also ask

How view state is maintained in MVC?

View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings.

Can we use view state in MVC?

ASP.NET MVC does not use ViewState in the traditional sense (that of storing the values of controls in the web page). Rather, the values of the controls are posted to a controller method.

Can you identify the correct steps for adding area to ASP NET core application?

Create ASP.NET Core MVC Area To add a new Area, Right Click on application name from solution explorer -> Select Add -> Select New Scaffolded Item -> select MVC Area from middle pane of dialog box -> Enter Name of Area -> Click Ok.

Which is a default view search path for the Razor view engine?

By default Razor Pages are stored in Pages folder under project root.


2 Answers

Great news... In ASP.NET Core 2 and up, you don't need a custom ViewEngine or even ExpandViewLocations anymore.

Using the OdeToCode.AddFeatureFolders Package

This is the easiest way... K. Scott Allen has a nuget package for you at OdeToCode.AddFeatureFolders that is clean and includes optional support for areas. Github: https://github.com/OdeToCode/AddFeatureFolders

Install the package, and it's as simple as:

public class Startup {     public void ConfigureServices(IServiceCollection services)     {         services.AddMvc()                 .AddFeatureFolders();          ...     }      ... }   

DIY

Use this if you need extremely fine control over your folder structure, or if you aren't allowed/don't want to take the dependency for whatever reason. This is also quite easy, although perhaps more cluttery than the nuget package above:

public class Startup {     public void ConfigureServices(IServiceCollection services)     {          ...           services.Configure<RazorViewEngineOptions>(o =>          {              // {2} is area, {1} is controller,{0} is the action                  o.ViewLocationFormats.Clear();               o.ViewLocationFormats.Add("/Controllers/{1}/Views/{0}" + RazorViewEngine.ViewExtension);              o.ViewLocationFormats.Add("/Controllers/Shared/Views/{0}" + RazorViewEngine.ViewExtension);               // Untested. You could remove this if you don't care about areas.              o.AreaViewLocationFormats.Clear();              o.AreaViewLocationFormats.Add("/Areas/{2}/Controllers/{1}/Views/{0}" + RazorViewEngine.ViewExtension);              o.AreaViewLocationFormats.Add("/Areas/{2}/Controllers/Shared/Views/{0}" + RazorViewEngine.ViewExtension);              o.AreaViewLocationFormats.Add("/Areas/Shared/Views/{0}" + RazorViewEngine.ViewExtension);         });          ...              }  ... } 

And that's it! No special classes required.

Dealing with Resharper/Rider

Bonus tip: if you're using ReSharper, you might notice that in some places ReSharper can't find your views and gives you annoying warnings. To work around that, pull in the Resharper.Annotations package and in your startup.cs (or anywhere else really) add one of these attributes for each of your view locations:

[assembly: AspMvcViewLocationFormat("/Controllers/{1}/Views/{0}.cshtml")] [assembly: AspMvcViewLocationFormat("/Controllers/Shared/Views/{0}.cshtml")]  [assembly: AspMvcViewLocationFormat("/Areas/{2}/Controllers/{1}/Views/{0}.cshtml")] [assembly: AspMvcViewLocationFormat("/Controllers/Shared/Views/{0}.cshtml")] 

Hopefully this spares some folks the hours of frustration I just lived through. :)

like image 190
Brian MacKay Avatar answered Sep 22 '22 21:09

Brian MacKay


You can expand the locations where the view engine looks for views by implementing a view location expander. Here is some sample code to demonstrate the approach:

public class ViewLocationExpander: IViewLocationExpander {      /// <summary>     /// Used to specify the locations that the view engine should search to      /// locate views.     /// </summary>     /// <param name="context"></param>     /// <param name="viewLocations"></param>     /// <returns></returns>     public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) {         //{2} is area, {1} is controller,{0} is the action         string[] locations = new string[] { "/Views/{2}/{1}/{0}.cshtml"};         return locations.Union(viewLocations);          //Add mvc default locations after ours     }       public void PopulateValues(ViewLocationExpanderContext context) {         context.Values["customviewlocation"] = nameof(ViewLocationExpander);     } } 

Then in the ConfigureServices(IServiceCollection services) method in the startup.cs file add the following code to register it with the IoC container. Do this right after services.AddMvc();

services.Configure<RazorViewEngineOptions>(options => {         options.ViewLocationExpanders.Add(new ViewLocationExpander());     }); 

Now you have a way to add any custom directory structure you want to the list of places the view engine looks for views, and partial views. Just add it to the locations string[]. Also, you can place a _ViewImports.cshtml file in the same directory or any parent directory and it will be found and merged with your views located in this new directory structure.

Update:
One nice thing about this approach is that it provides more flexibility then the approach later introduced in ASP.NET Core 2 (Thanks @BrianMacKay for documenting the new approach). So for example this ViewLocationExpander approach allows for not only specifying a hierarchy of paths to search for views and areas but also for layouts and view components. Also you have access to the full ActionContext to determine what an appropriate route might be. This provides alot of flexibility and power. So for example if you wanted to determine the appropriate view location by evaluating the path of the current request, you can get access to the path of the current request via context.ActionContext.HttpContext.Request.Path.

like image 29
RonC Avatar answered Sep 22 '22 21:09

RonC