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

I want to create a wrapper around this existing helper:

@Content.Url("...")

How to create an assistant to transfer it and add a parameter to it?

My controller has the property:

public bool IsAdmin {get; set;}

I want to somehow associate this value with my controller and use it like:

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

How can i do this? The only way to add IsAdminto mine ViewModel?

+5
source share
2 answers

You can add IsAdminto your model or make it a static property that stores the value in HttpContext.Current.Items. Alternatively, it can dynamically read the value 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 your own extension method like this

public static Content(this UrlHelper helper, string contentPath, bool isAdmin)
{
    // do something with isAdmin
    helper.Content(contentPath);
}
+2

- , :

public class UrlHelperEx : UrlHelper
{
    #region Constants
    private const string c_VERSION_FORMAT = "{0}?v={1}";
    #endregion

    #region Initialization
    public UrlHelperEx(RequestContext requestContext)
        : base(requestContext)
    {
    }
    #endregion

    #region Public methods
    public string Content(string contentPath,bool forceupdate=false)
    {
        var content = base.Content(contentPath);

        if (!forceupdate) {
            return content.ToString();
        }
        else
        { 
            Version version = WebHelper.GetApplicationVersion(this.RequestContext.HttpContext);
            return string.Format(c_VERSION_FORMAT, content
                    , version.ToString());
        }
    }
    #endregion  
}
0

All Articles