Método HTML.ActionLink

Resuelto Graviton asked hace 15 años • 10 respuestas

digamos que tengo una clase

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

En una página que no está ubicada en la carpeta Elemento, donde ItemControllerreside, quiero crear un enlace al Loginmétodo. entonces cualHtml.ActionLink método debo utilizar y qué parámetros debo pasar?

Específicamente estoy buscando el reemplazo del método.

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

que se ha retirado en la reciente encarnación de ASP.NET MVC.

Graviton avatar Oct 14 '08 16:10 Graviton
Aceptado

Creo que lo que quieres es esto:

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

Esto utiliza el siguiente método de firma ActionLink:

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

ASP.NET MVC2

Se han intercambiado dos argumentos.

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

Esto utiliza el siguiente método de firma ActionLink:

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

ASP.NET MVC3+

Los argumentos están en el mismo orden que MVC2, sin embargo, el valor de identificación ya no es necesario:

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

Esto evita codificar cualquier lógica de enrutamiento en el enlace.

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

Esto le dará el siguiente resultado html, suponiendo:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. todavía tienes la siguiente ruta definida

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);
Joseph Kingry avatar Oct 14 '2008 14:10 Joseph Kingry

Quería agregar algo a la respuesta de Joseph Kingry . Él me proporcionó la solución, pero al principio tampoco pude hacer que funcionara y obtuve un resultado similar al de Adhip Gupta. Y luego me di cuenta de que, en primer lugar, la ruta tiene que existir y los parámetros deben coincidir exactamente con la ruta. Entonces tenía una identificación y luego un parámetro de texto para mi ruta que también debía incluirse.

Html.ActionLink(article.Title, "Login", "Item", new { id = article.ArticleID, title = article.Title }, null)
Jeff Widmer avatar Mar 09 '2009 11:03 Jeff Widmer

Es posible que desee consultar el RouteLink()método. Éste le permite especificar todo (excepto el texto del enlace y el nombre de la ruta) a través de un diccionario.

Haacked avatar Oct 14 '2008 15:10 Haacked