简体   繁体   English

如何围绕Url.Content辅助函数创建包装器帮助器?

[英]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 ? 是将IsAdmin添加到我的ViewModel的唯一方法吗?

You can either add IsAdmin to your model or make it a static property that stores the value in HttpContext.Current.Items . 您可以将IsAdmin添加到模型中,也可以将其设置为将值存储在HttpContext.Current.Items的静态属性。 Alternatively it can read the value dynamically from HttpContext.Request . 或者,它可以从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  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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