2010-05-24 20 views
10

Czy ktoś może wyjaśnić, dlaczego następujące czynności? I jak rozwiązać, Visual Studio 2010 i MVC2Asp.Net MVC ActionLink

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

Wyniki w

/Produkt/AddOption? Class = schowka

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

Skutkuje

/Produkt/AddOption? Length = 7

Dzięki

Odpowiedz

20

Używasz tych odpowiednich przeciążeń:

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

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

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

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

Pierwszy new { @class = "lighbox" } przepuszcza jako argument routeValues, gdy powinien być argumentem htmlAttributes.

Ten rodzaj problemu jest powszechny w przypadku metod rozszerzania używanych w MVC. W czasami może pomóc w obsłudze nazwanych argumentów (C# 4.0), aby uczynić to bardziej czytelne:

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

To jest przykład z "piekła" przeciążenia w ASP.NET MVC.

Pierwszy kod wywołuje następujące metody:

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

natomiast drugi kod wywołuje ten jeden:

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

Zauważ, że parametr ciąg controllerName w pierwszej rozmowy staje routeValues w sekundę jeden. Wartość ciągu "Produkt" jest przekazywana do trasowanych wartości: używana jest właściwość string Length, która ma tutaj długość 7, stąd "Długość = 7", którą dostajesz na trasie.

Biorąc pod uwagę pierwszą metodę, wydaje się, że zamieniłeś parametry routeValues i htmlAttributes.

Powiązane problemy