Asp.Net MVC ActionLink

Lia*_*amB 10 asp.net asp.net-mvc extension-methods asp.net-mvc-2

谁能解释为什么会发生以下情况?以及如何解决,Visual Studio 2010和MVC2

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

结果是

/产品/ AddOption?CLASS =收藏夹

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

结果是

/产品/ AddOption?长度= 7

谢谢

Dav*_*ale 20

您正在使用这些相应的重载:

public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

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

public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
Object routeValues,
Object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

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

当它应该是参数时,第一个new { @class = "lighbox" }作为routeValues参数传递htmlAttributes.

这种问题在MVC中使用的扩展方法很常见.有时可以帮助使用命名参数(C#4.0)来使事情更具可读性:

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


Jul*_*ain 10

这是ASP.NET MVC中"重载地狱"的一个例子.

第一个代码调用以下方法:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

而第二个代码称之为:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    Object routeValues,
    Object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

请注意,controllerName第一个调用中的字符串参数正在变为routeValues第二个调用中.字符串值"Product"被传递给路由值:使用字符串属性Length,此处长度为7,因此您在路径中获得"长度= 7".

考虑到第一种方法,似乎你已经交换了routeValueshtmlAttributes参数.