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

时间:2013-04-22 19:16:47

标签: c# asp.net-mvc asp.net-mvc-4

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

@Content.Url("...")

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

我的控制器有一个属性:

public bool IsAdmin {get; set;}

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

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

我该怎么做?是IsAdmin添加ViewModel的唯一方法吗?

2 个答案:

答案 0 :(得分:2)

您可以将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);
}

答案 1 :(得分:0)

Here是您正在寻找的一个很好的例子:

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  
}