繁体   English   中英

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

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

我想围绕这个现有的帮助器创建一个包装器:

@Content.Url("...")

如何创建一个帮助程序来包装它并为其添加参数?

我的控制器有一个属性:

public bool IsAdmin {get; set;}

我想以某种方式从我的控制器引用这个值,并使用它像:

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

我怎样才能做到这一点? 是将IsAdmin添加到我的ViewModel的唯一方法吗?

您可以将IsAdmin添加到模型中,也可以将其设置为将值存储在HttpContext.Current.Items的静态属性。 或者,它可以从HttpContext.Request动态读取值。

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

您可以像这样创建自定义扩展方法

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

是您正在寻找的一个非常好的例子:

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