创建自定义ActionLink

时间:2014-09-10 10:36:32

标签: asp.net-mvc asp.net-mvc-4 html-helper actionlink

我想创建一个自定义动作链接但我不知道如何在满足我的需求的同时做到这一点。之前我使用过自定义htmlhelpers,但这对我来说有点棘手。

我想要呼叫的actionlink必须是这样的:

@Html.CustomActionLink("LinkText", "Area","Controller","TabMenu","Action",routeValues, htmlAttributes)

所以一个例子是:

 @Html.CustomActionLink("Click here","Travel","Trip","Index","Index", new { par1 = "test", par2 = test2, new { @class = "font-color-blue" })`

会产生这个html:

<a class="font-color-blue" href="/Trip/Travel/Index/Index?par1=test&par2=test2">Click Here</a>

我的路线如下:

 context.MapRoute(
            "EPloeg_default",
            "EPloeg/{controller}/{tabmenu}/{action}/{id}/{actionMethod}",
            new { action = "Index", id = UrlParameter.Optional, actionMethod = UrlParameter.Optional }
        );   

我有什么想法可以做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以实现自定义Action Link扩展,您必须在LinkExtensions类中编写自己的方法:

namespace TestCustomHelper.Html
{

public static class LinkExtensions
{
public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool showActionLinkAsDisabled)
  {
     if (htmlHelper.ActionAuthorized(actionName, controllerName))
     {
       return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
     }
     return MvcHtmlString.Empty;
}

}

并在视图中使用它:

@using TestCustomHelper.Html


@Html.ActionLinkAuthorized("Create New", "Create", new { org = ViewBag.OrgBranchID }, new { @id = "linkCreateEmployee" },true) 

注意:

如果您看到方法的最后一个参数,我添加了一个extara bool参数,您可以根据需要添加更多参数。

我根据我的需要为它写了一个重载,你可以写Html.ActionLink()所有的重载。

查看我的tutorial on Creating Custom Html Helper Extensions in asp.net mvc

另见Official asp.net mvc Creating Custom HTML Helpers

更新

您可能希望看到我的this answer in which custom Action Link I wrote

答案 1 :(得分:2)

以下代码怎么样,

@Html.ActionLink("Click here","Trip","Index", new { area= "Travel", tabmenu= "Index"}, new { @class = "font-color-blue" })

修改

你可以使用像这样的扩展方法,

public static MvcHtmlString CustomActionLink(this HtmlHelper htmlHelper, string linkText, string area, string controller, string tabMenu, string action, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
{
    routeValues.Add("area", area);
    routeValues.Add("tabMenu", tabMenu);
    return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
}