Agung Setiawan
Agung Setiawan

Reputation: 1164

ASP.NET ControllerBase Extension Method Doesn't Work on Razor View

I've created extension method like below

public static class RBACExtension
{
    public static bool HasPermission(this ControllerBase controller, string permission)
    {
       // some implementation 
    }
}

It works fine inside a controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        this.HasPermission("somePermission");
        return View();
    }
}

But it doesn't work inside Razor. When I want to use the method it doesn't show up on autocomplete.

ViewContext.Controller.HasPermission("somePermission")

How to make it available inside Razor view?

Upvotes: 1

Views: 3462

Answers (2)

DavidG
DavidG

Reputation: 119066

ViewContext.Controller is the Controller class, not your base controller class. This is a bit of an awkward way to do this though as it couples your controllers to your views. Instead make an extension method (as a custom HtmlHelper is a great way), for exmaple:

public static class MyExtensions
{
    public static bool HasPermission(this HtmlHelper helper, string permission)
    {
        // blah
    }
}

And use in Razor like this:

@Html.HasPermission("admin")

Alternatively put the method in a class inherited from WebViewPage for use in your Razor view. For example:

public abstract class MyBaseViewPage : WebViewPage
{
    public bool HasPermission(string permission)
    {
        // blah
    }
}

Then make your Razor pages use it by editing your Views/web.config

<pages pageBaseType="YourProject.MyBaseViewPage">

And now in Razor you can simply do this:

@HasPermission("admin")

Upvotes: 2

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17784

put extension method in a namespace like

namespace mynamespace.extensions{
public static class RBACExtension
{
    public static bool HasPermission(this ControllerBase controller, string permission)
    {
       // some implementation 
    }
 }
}

and put a using statement at top of your view like

@using mynamespace.extensions

Then this method will be available in your view

Upvotes: 3

Related Questions