Asp.net

Asp.Net MVC 動作連結

  • May 24, 2010

誰能解釋為什麼會發生以下情況?以及如何解決,Visual Studio 2010 和 MVC2

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

結果是

/Product/AddOption?class=燈箱

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

結果是

/Product/AddOption?Length=7

謝謝

您正在使用這些各自的重載:

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

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

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

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

當它應該是參數時,第一個new { @class = "lighbox" }作為參數傳遞。routeValues``htmlAttributes

這種問題在 MVC 中使用的擴展方法中很常見。In 有時可以幫助使用命名參數(C# 4.0) 使事情更具可讀性:

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

引用自:https://stackoverflow.com/questions/2897481