DmitryEfimenko / TwitterBootstrapMvc

Fluent implementation of ASP.NET-MVC HTML helpers for Twitter Bootstrap.
Apache License 2.0
224 stars 79 forks source link

Intercept the ActionLink render pipeline #387

Closed Sarmaad closed 9 years ago

Sarmaad commented 9 years ago

I have a requirement to validate the rendering of the html control based on user permissions.

I have an extension method: public static BootstrapActionLinkBase<'T'> SecurityAware<'T'>(this BootstrapActionLinkBase<'T'> linkBase) where TModel : BootstrapActionLinkBase<'T'>

used @Html.Bootstrap().ActionLink("Settings", "Index", "Setting").SecurityAware().PrependIcon("fa fa-cogs")

To intercept the pipeline and trying to evaluate the action method on the controller against the current user.

I would like to have the ability to access the model to:

any help would be appreciated.

DmitryEfimenko commented 9 years ago

the model that contains all the stuff that you need is a protected property. It's not made public because if it was that, it'd be showing in the intellisense when you type @Html.Bootstrap().ActionLink("Settings", "Index", "Setting")., which is not desirable.

What you can do instead of writing an extension is writing a separate helper:

public static class BmvcExtensions
{
    public static ActionLinkAuthorized ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName)
    {
        string controllerName =  htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
        return new ActionLinkAuthorized(htmlHelper, linkText, actionName, controllerName);
    }
    public static ActionLinkAuthorized ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
    {
        return new ActionLinkAuthorized(htmlHelper, linkText, actionName, controllerName);
    }
}

public class ActionLinkAuthorized : BootstrapActionLink
{
    public ActionLinkAuthorized(HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
        : base(htmlHelper, linkText, actionName, controllerName)
    {
        //TODO: condition to check if action is authorized:
        if (true/*your logic for authorizing*/)
        {
            base._model.ShouldNotRender = true;
        }
    }
}

You'd use it like so:

@Html.ActionLinkAuthorized("text", "action", "controller")
Sarmaad commented 9 years ago

That worked perfectly..

Thank you