2010-05-24 18 views
10

Qualcuno può spiegare perché succede? E come risolvere, Visual Studio 2010 e MVC2Asp.Net MVC ActionLink

<%= Html.ActionLink("Add New Option", "AddOption", "Product", new { @class = "lighbox" }, null)%> 

Risultati in

/prodotto/AddOption? Class = lightbox

<%= Html.ActionLink("Add New Option", "AddOption", "Product", new { @class = "lighbox" })%> 

Risultati in

/Product/AddOption? Length = 7

Grazie

risposta

20

Stai utilizzando questi rispettivi sovraccarichi:

public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper, 
string linkText, 
string actionName, 
string controllerName, 
Object routeValues, 
Object htmlAttributes 
) 

Da: http://msdn.microsoft.com/en-us/library/dd504972.aspx

public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper, 
string linkText, 
string actionName, 
Object routeValues, 
Object htmlAttributes 
) 

Da: http://msdn.microsoft.com/en-us/library/dd492124.aspx

Il primo new { @class = "lighbox" } è passato come argomento routeValues quando dovrebbe essere l'argomento htmlAttributes.

Questo tipo di problema è comune con i metodi di estensione utilizzati in MVC. In a volte può aiutare a utilizzare denominati argomenti (C# 4.0) per rendere le cose più leggibile:

<%= Html.ActionLink(linkText: "Add New Option", 
    actionName: "AddOption", 
    controllerName: "Product", 
    htmlAttributes: new { @class = "lighbox" }, 
    routeValues: null)%> 
9

Questo è un esempio di "sovraccarico inferno" in ASP.NET MVC.

Il primo codice chiama il seguente metodo:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper, 
    string linkText, 
    string actionName, 
    string controllerName, 
    Object routeValues, 
    Object htmlAttributes 
) 

mentre il secondo codice chiama questo:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper, 
    string linkText, 
    string actionName, 
    Object routeValues, 
    Object htmlAttributes 
) 

Si noti che il parametro di stringa controllerName nella prima chiamata sta diventando routeValues nella seconda uno. Il valore stringa "Prodotto" viene passato ai valori instradati: viene utilizzata la proprietà stringa Length, che ha una lunghezza di 7 qui, quindi "Lunghezza = 7" che stai ricevendo nel percorso.

Considerando il primo metodo, sembra che abbiate invertito i parametri routeValues e htmlAttributes.

Problemi correlati