简体   繁体   中英

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 ?

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);
}

Here is a very good example of what you are looking for:

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  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM