HTML.ActionLink-methode

Stel dat ik les heb

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

Op een pagina die zich niet in de itemmap bevindt, waar ItemControllerzich bevindt, wil ik een link maken naar de Login-methode. Dus welke Html.ActionLink-methode moet ik gebruiken en welke parameters moet ik doorgeven?

In het bijzonder ben ik op zoek naar de vervanging van de methode

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

die met pensioen is gegaan in de recente incarnatie van ASP.NET MVC.


Antwoord 1, autoriteit 100%

Ik denk dat je dit wilt:

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).
                )

Dit gebruikt de volgende methode ActionLink-handtekening:

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

ASP.NET MVC2

twee argumenten zijn omgedraaid

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).
                )

Dit gebruikt de volgende methode ActionLink-handtekening:

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

ASP.NET MVC3+

argumenten staan in dezelfde volgorde als MVC2, maar de id-waarde is niet langer vereist:

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).
                )

Dit vermijdt het hard coderen van routeringslogica in de link.

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

Dit geeft u de volgende html-uitvoer, ervan uitgaande:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. je hebt nog steeds de volgende route gedefinieerd

.
.

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

Antwoord 2, autoriteit 6%

Ik wilde iets toevoegen aan Joseph Kingry’s antwoord. Hij bood de oplossing maar in eerste instantie kreeg ik het ook niet werkend en kreeg een resultaat net als Adhip Gupta. En toen realiseerde ik me dat de route in de eerste plaats moet bestaan en dat de parameters precies op de route moeten passen. Dus ik had een id en vervolgens een tekstparameter voor mijn route die ook moest worden opgenomen.

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

Antwoord 3, autoriteit 3%

Misschien wil je de RouteLink()methode. Hiermee kun je alles specificeren (behalve de linktekst en routenaam) via een woordenboek.


Antwoord 4, autoriteit 3%

Ik denk dat Joseph de controller en actie omdraaide. Eerst komt de actie, dan de controller. Dit is enigszins vreemd, maar de manier waarop de handtekening eruit ziet.

Ter verduidelijking, dit is de versie die werkt (aanpassing van het voorbeeld van Joseph):

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

Antwoord 5, autoriteit 2%

hoe zit dit

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

Antwoord 6, autoriteit 2%

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

Antwoord 7, autoriteit 2%

Als je helemaal voor een fancy-pants wilt gaan, kun je het als volgt verlengen om dit te kunnen doen:

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

U moet dit in de System.Web.Mvcnaamruimte plaatsen:

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;
    }
}

Dit omvat twee overschrijvingen voor Route Valuesen HTML Attributes, en al uw weergaven zouden moeten toevoegen: @using YourProject.Controllersof u kunt het toevoegen aan uw web.config <pages><namespaces>


Antwoord 8

Gebruik benoemde parameters voor leesbaarheid en om verwarring te voorkomen.

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

Antwoord 9

Met MVC5 heb ik het zo gedaan en het is 100% werkende code….

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

jullie kunnen hiervan een idee krijgen …


Antwoord 10

Dit type gebruik:

@ html.actionlink (“mainpage”, “index”, “Home”)

MAINPAGE: NAAM VAN DE TEKST
Index: Actiezicht
Home: HomeController

BASE GEBRUIK ACTICTIONLINK

<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>

Other episodes