Click here to Skip to main content
15,867,949 members
Articles / All Topics

Custom View Engine in ASP.NET 5

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Sep 2015MIT 8.4K   1   2
This post is about implementing Custom View Engine in ASP.NET 5. Normally ASP.NET MVC looks for view files (*.cshtml), inside Views/Controller folder. If you want to configure it to some other location, you can manage it via custom view engine. Here is the implementation.

This post is about implementing Custom View Engine in ASP.NET 5. Normally ASP.NET MVC looks for view files (*.cshtml), inside Views/Controller folder. If you want to configure it to some other location, you can manage it via custom view engine. Here is the implementation.

public class CustomUIViewEngine : RazorViewEngine
{
    public CustomUIViewEngine(IRazorPageFactory pageFactory,
       IRazorViewFactory viewFactory,
       IOptions<RazorViewEngineOptions> optionsAccessor,
       IViewLocationCache viewLocationCache) :
       base(pageFactory, viewFactory, optionsAccessor, viewLocationCache)
    {
    }
    public override IEnumerable<string> ViewLocationFormats
    {
        get
        {
            var viewLocationFormats = base.ViewLocationFormats
            .Union(new string[]{ "~/Views/{1}/UI/{0}.cshtml" });
            return viewLocationFormats;
        }
    }
}

This implementation is different than custom view engine implementation in previous versions of ASP.NET MVC. In ASP.NET MVC 5 or previous, ViewLocationFormats added in the constructor, but it is not possible, since ViewLocationFormats property is readonly.

Here is the modified folder structure include UI folder.

Modified folder structure with UI folder

Modified folder structure with UI folder

You can configure this view engine in the Startup.cs, ConfigureServices() method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcViewOptions>(options =>{
        options.ViewEngines.Clear();
        options.ViewEngines.Add(typeof(CustomUIViewEngine));
    });
}

This code is clearing the existing view engines and adding the new custom view engine.

Happy Programming :)

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Technical Lead
India India
Working as Tech. Lead

My blog : dotnetthoughts.net.
You can follow me in twitter : @anuraj

Comments and Discussions

 
QuestionWhat version release of MVC 5, were you using? Pin
Sen Gupta4-Mar-16 11:15
Sen Gupta4-Mar-16 11:15 
AnswerRe: What version release of MVC 5, were you using? Pin
Nacho Baez29-Jul-16 12:20
Nacho Baez29-Jul-16 12:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.