Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a wrapper helper around Url.Content helper function?

I want to create a wrapper around this existing helper:

@Content.Url("...")

How can I create a helper to wrap this and add a parameter to it?

My Controller has a property:

public bool IsAdmin {get; set;}

I want to somehow reference this value from my controller and use it like:

@MyContent.Url("...", IsAdmin)

How can I do this? Is the only way to add IsAdmin to my ViewModel?

like image 724
loyalflow Avatar asked Nov 03 '22 23:11

loyalflow


1 Answers

You can either add IsAdmin to your model or make it a static property that stores the value in HttpContext.Current.Items. Alternatively it can read the value dynamically from HttpContext.Request.

public static bool IsAdmin
{
    get { return (HttpContext.Current.Items["IsAdmin"] as bool?) ?? false; }
    set { HttpContext.Current.Items["IsAdmin"] = value; }
}

You can create a custom extension method like this

public static Content(this UrlHelper helper, string contentPath, bool isAdmin)
{
    // do something with isAdmin
    helper.Content(contentPath);
}
like image 128
Knaģis Avatar answered Nov 12 '22 15:11

Knaģis