如何覆盖Url.Action

时间:2015-02-09 18:45:00

标签: c# asp.net-mvc asp.net-mvc-3 extension-methods

现在我用来覆盖像:

这样的扩展名
public abstract class MyWebViewPage<T> : WebViewPage<T>
{
    public new MyHtmlHelper<T> Html { get; set; }
    public override void InitHelpers()
    {
        Ajax = new AjaxHelper<T>(ViewContext, this);
        Url = new UrlHelper(ViewContext.RequestContext);
        Html = new MyHtmlHelper<T>(ViewContext, this);
    }
}

public class MyHtmlHelper<T> : HtmlHelper<T>
{
    public MyHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer) :
        base(viewContext, viewDataContainer)
    {
    }

    public MvcHtmlString ActionLink(string linkText, string actionName)
    {
        return ActionLink(linkText, actionName, null, new RouteValueDictionary(), new RouteValueDictionary());
    } 
}

如何使用所有重载版本添加Url.Action助手?

UPD:我应该覆盖所有标准方法,因为很多人都在这方面工作,我应该使用标准助手但我的功能

1 个答案:

答案 0 :(得分:8)

您无需覆盖Url.Action帮助程序和HtmlHelper操作。您可以改为创建Extension Methods。这是一个例子:

public static class MyHelpers
{
    public static string MyAction(this UrlHelper url, string actionName)
    {
        // return whatever you want (here's an example)...
        return url.Action(actionName, new RouteValueDictionary());
    }
}

然后,您可以在视图中使用此方法:

@Url.MyAction("MyActionName")

<强>更新

我不建议覆盖Url.Action方法。创建扩展方法更容易,更清洁。但是,这是你可以做到的:

public class MyUrlHelper : UrlHelper 
{
    public override string Action(string actionName)
    {
        return base.Action(actionName, new RouteValueDictionary());  
    }
}