DotNetSlackers: ASP.NET News for lazy Developers

Tuesday, October 13, 2015

Overriding/Changing Base Razor View Page Type in ASP.NET 5 (vnext)

   Introduction:

                 Using razor views, sometimes we might need additional class properties/methods in all our views than we have in the existing built-in base razor view. For example, our all view pages might need title, keywords, etc. In ASP.NET 5, we can easily create a base razor view page class and set this class as a base razor view type for all our views. In this post, I will show you an example of this.   

        Description:

                    Note that I am using beta7 at the time of writing. Razor views are inherit from generic Microsoft.AspNet.Mvc.Razor.RazorPage class. We can create our custom base razor view class by inheriting RazorPage class,

1public abstract class MyRazorPage<T> : RazorPage<T>
2{
3    public string Title { get; set; }
4    public string Description { get; set; }
5    public string[] Keywords { get; set; }
6}
                    We have added three more properties in our base view. Now for making this class as our base razor view globally, we can register it in _ViewImports.cshtml file,

1@inherits MyNameSpace.MyRazorPage<TModel>

                    Now we can use the new properties (Title, Description and Keywords) anywhere in our view.

        Summary:

                    In this article, I showed you an example of how to create a base razor view page and then how to register this class globally.

No comments:

Post a Comment