C# HTML.ActionLink 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/200476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:46:01  来源:igfitidea点击:

HTML.ActionLink method

c#.netasp.net-mvchtml-helperactionlink

提问by Graviton

Let's say I have a class

假设我有一堂课

public class ItemController:Controller
{
    public ActionResult Login(int id)
    {
        return View("Hi", id);
    }
}

On a page that is not located at the Item folder, where ItemControllerresides, I want to create a link to the Loginmethod. So which Html.ActionLinkmethod I should use and what parameters should I pass?

在不位于 Item 文件夹(所在的位置)的页面上ItemController,我想创建指向该Login方法的链接。那么Html.ActionLink我应该使用哪种方法以及我应该传递哪些参数?

Specifically, I am looking for the replacement of the method

具体来说,我正在寻找方法的替换

Html.ActionLink(article.Title,
    new { controller = "Articles", action = "Details",
          id = article.ArticleID })

that has been retired in the recent ASP.NET MVC incarnation.

已在最近的 ASP.NET MVC 版本中退役。

采纳答案by Joseph Kingry

I think what you want is this:

我想你想要的是这个:

ASP.NET MVC1

ASP.NET MVC1

Html.ActionLink(article.Title, 
                "Login",  // <-- Controller Name.
                "Item",   // <-- ActionMethod
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

这使用以下方法 ActionLink 签名:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string controllerName,
                                string actionName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC2

ASP.NET MVC2

two arguments have been switched around

两个论点已经互换

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

这使用以下方法 ActionLink 签名:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC3+

ASP.NET MVC3+

arguments are in the same order as MVC2, however the id value is no longer required:

参数与 MVC2 的顺序相同,但不再需要 id 值:

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This avoids hard-coding any routing logic into the link.

这避免了将任何路由逻辑硬编码到链路中。

 <a href="/Item/Login/5">Title</a> 

This will give you the following html output, assuming:

这将为您提供以下 html 输出,假设:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. you still have the following route defined
  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. 您仍然定义了以下路线

. .

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

回答by Adhip Gupta

Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item") 

回答by Haacked

You might want to look at the RouteLink()method.That one lets you specify everything (except the link text and route name) via a dictionary.

您可能想查看该RouteLink()方法。该方法可让您通过字典指定所有内容(链接文本和路由名称除外)。

回答by Jeff Widmer

I wanted to add to Joseph Kingry's answer. He provided the solution but at first I couldn't get it to work either and got a result just like Adhip Gupta. And then I realized that the route has to exist in the first place and the parameters need to match the route exactly. So I had an id and then a text parameter for my route which also needed to be included too.

我想补充一下约瑟夫金瑞的回答。他提供了解决方案,但起初我也无法让它发挥作用,结果就像 Adhip Gupta 一样。然后我意识到路线必须首先存在并且参数需要与路线完全匹配。所以我有一个 id,然后是我的路线的文本参数,它也需要包含在内。

Html.ActionLink(article.Title, "Login", "Item", new { id = article.ArticleID, title = article.Title }, null)

回答by agez

I think that Joseph flipped controller and action. First comes the action then the controller. This is somewhat strange, but the way the signature looks.

我认为约瑟夫翻转了控制器和动作。首先是动作,然后是控制器。这有点奇怪,但签名的样子。

Just to clarify things, this is the version that works (adaption of Joseph's example):

只是为了澄清事情,这是有效的版本(约瑟夫的例子改编):

Html.ActionLink(article.Title, 
    "Login",  // <-- ActionMethod
    "Item",   // <-- Controller Name
    new { id = article.ArticleID }, // <-- Route arguments.
    null  // <-- htmlArguments .. which are none
    )

回答by Hasan

what about this

那这个呢

<%=Html.ActionLink("Get Involved", 
                   "Show", 
                   "Home", 
                   new 
                       { 
                           id = "GetInvolved" 
                       }, 
                   new { 
                           @class = "menuitem", 
                           id = "menu_getinvolved" 
                       }
                   )%>

回答by Serj Sagan

If you want to go all fancy-pants, here's how you can extend it to be able to do this:

如果您想使用所有花哨的裤子,以下是您可以扩展它以执行此操作的方法:

@(Html.ActionLink<ArticlesController>(x => x.Details(), article.Title, new { id = article.ArticleID }))

You will need to put this in the System.Web.Mvcnamespace:

你需要把它放在System.Web.Mvc命名空间中:

public static class MyProjectExtensions
{
    public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName));
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    public static MvcHtmlString ActionLink<TController, TAction>(this HtmlHelper htmlHelper, Expression<Action<TController, TAction>> expression, string linkText, object routeValues)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText, object routeValues, object htmlAttributes) where TController : Controller
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var attributes = AnonymousObjectToKeyValue(htmlAttributes);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
        link.MergeAttributes(attributes, true);
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    private static Dictionary<string, object> AnonymousObjectToKeyValue(object anonymousObject)
    {
        var dictionary = new Dictionary<string, object>();

        if (anonymousObject == null) return dictionary;

        foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
        {
            dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));
        }

        return dictionary;
    }
}

This includes two overrides for Route Valuesand HTML Attributes, also, all of your views would need to add: @using YourProject.Controllersor you can add it to your web.config <pages><namespaces>

这包括对Route Valuesand 的两个覆盖HTML Attributes,此外,您的所有视图都需要添加:@using YourProject.Controllers或者您可以将其添加到您的web.config <pages><namespaces>

回答by Sohail Malik

With MVC5 i have done it like this and it is 100% working code....

使用 MVC5 我已经这样做了,它是 100% 工作代码....

@Html.ActionLink(department.Name, "Index", "Employee", new { 
                            departmentId = department.DepartmentID }, null)

You guys can get an idea from this...

小伙伴们可以从这个思路...

回答by guneysus

Use named parameters for readability and to avoid confusions.

使用命名参数以提高可读性并避免混淆。

@Html.ActionLink(
            linkText: "Click Here",
            actionName: "Action",
            controllerName: "Home",
            routeValues: new { Identity = 2577 },
            htmlAttributes: null)

回答by Serdin ?elik

This type use:

这种类型使用:

@Html.ActionLink("MainPage","Index","Home")

@Html.ActionLink("MainPage","Index","Home")

MainPage : Name of the text Index : Action View Home : HomeController

MainPage:文本名称索引:Action View Home:HomeController

Base Use ActionLink

基本使用操作链接

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>_Layout</title>
    <link href="@Url.Content("~/Content/bootsrap.min.css")" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="container">
        <div class="col-md-12">
            <button class="btn btn-default" type="submit">@Html.ActionLink("AnaSayfa","Index","Home")</button>
            <button class="btn btn-default" type="submit">@Html.ActionLink("Hakk?m?zda", "Hakkimizda", "Home")</button>
            <button class="btn btn-default" type="submit">@Html.ActionLink("Ileti?im", "Iletisim", "Home")</button>
        </div> 
        @RenderBody()
        <div class="col-md-12" style="height:200px;background-image:url(/img/footer.jpg)">

        </div>
    </div>
</body>
</html>