简体   繁体   English

HTML.ActionLink方法

[英]HTML.ActionLink method

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 ItemController resides, I want to create a link to the Login method. 在不在ItemController所在的Item文件夹的页面上,我想创建一个指向Login方法的链接。 So which Html.ActionLink method I should use and what parameters should I pass? 那么我应该使用哪种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化身中退役了。

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 您仍然定义了以下路线

. .

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

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. 他提供了解决方案,但起初我无法让它工作,并得到像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. 所以我有一个id,然后是我的路线的文本参数,也需要包含它。

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

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

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
    )

what about this 那这个呢

<%=Html.ActionLink("Get Involved", 
                   "Show", 
                   "Home", 
                   new 
                       { 
                           id = "GetInvolved" 
                       }, 
                   new { 
                           @class = "menuitem", 
                           id = "menu_getinvolved" 
                       }
                   )%>
Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item") 

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.Mvc namespace: 您需要将它放在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 Values and HTML Attributes , also, all of your views would need to add: @using YourProject.Controllers or you can add it to your web.config <pages><namespaces> 这包括Route ValuesHTML Attributes两个覆盖,同样,您需要添加所有视图: @using YourProject.Controllers或者您可以将其添加到您的web.config <pages><namespaces>

Use named parameters for readability and to avoid confusions. 使用命名参数以提高可读性并避免混淆。

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

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... 你们可以从中得到一个想法......

This type use: 此类型使用:

@Html.ActionLink("MainPage","Index","Home") @ Html.ActionLink( “的MainPage”, “索引”, “家”)

MainPage : Name of the text Index : Action View Home : HomeController MainPage:文本名称索引:Action View Home:HomeController

Base Use ActionLink 基础使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM