ASP. Instance code for Core custom View lookup location in net

  • 2021-11-13 01:23:31
  • OfStack

The contents of. NET Core can be seen everywhere, which has exploded all major communities around the world. Therefore, Lao Zhou believes that all the big partners have seen a lot. Therefore, Lao Zhou does not consider writing one knowledge point at a time, which will become the biggest bullshit of the year, and the official documents are also very detailed. Lao Zhou mainly talks about the contents that big partners may wonder when they get started.

ASP. NET Core can mix Web Pages and MVC in one project, which is what Lao Zhou wants most, because it will become more flexible. Web Pages is similar to our previous Web development approach, on a page-by-page basis, and this model focuses on functional partition. While MVC focuses on data, what kind of data model has what kind of Controller, what kind of Controller will correspond to what kind of Action, and Action will correspond to UI, that is, View. Therefore, MVC is data-centered.

PopulateValues (): Exists as a way to specify parameters, and your view lookup varies from request to request. Since you did not populate it, the view engine uses the cached value from the previous request.


public class ThemeViewLocationExpander : IViewLocationExpander
  {
    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
      string theme = context.Values["theme"];
      if (string.IsNullOrWhiteSpace(theme))
      {
        theme = "default";
      }
      string[] newLocation = { $"Views/{theme}/{{1}}/{{0}}.cshtml"};
      return viewLocations.Union(newLocation);
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {
      context.Values["theme"] = context.ActionContext.HttpContext.Request.Query["theme"].ToString();
    }
  }

// Configure template view path 
      services.Configure<RazorViewEngineOptions>(options =>
      {
        options.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
      });

Related articles: