Extending cshtml with functions and properties

Hey, Lately I've been building many infrastructures for my company's website and I wanted to expose those infrastructures in the most natural way that coders are used to.
One of the problems I spent time on was exposing the infrastructures on *.cshtml files.
I didn't want to use static classes - because it's not a natural way, and not very trivial.
So I managed to extend the class that represents the view, and by that add more properties and functions to it.
public abstract class ViewBase<TModel> : WebViewPage<TModel> where TModel : class
{
    public LayoutConfiguration LayoutConfiguration { get; private set; }

    public ViewBase()
    {
        LayoutConfiguration = LayoutConfiguration.GetInstance();
    }

    public void DoWork()
    {
  
    }
}
And now on your Web.config (in the Views folder) replace this line:
<pages pageBaseType="System.Web.Mvc.WebViewPage">
With this one:
<pages pageBaseType="namespace.ViewBase">
And then on cshtml you can access the code:
@{    
    LayoutConfiguration.PageLabel = "HomepageBusiness";
    DoWork();
}

This way is much more elegant to adding extensions on HtmlHelper, or using static classes.

Comments

Popular posts from this blog

Impersonating CurrentUser from SYSTEM

Add Styles & Scripts Dynamically to head tag in ASP .NET MVC

Json To Dictionary generic model binder