开发者

Asp.Net MVC ActionLink

开发者 https://www.devze.com 2022-12-31 16:08 出处:网络
Can anyone explain why the following happens? And how to resolve, Visual Studio 2010 and MVC2 <%= Html.Act开发者_C百科ionLink(\"Add New Option\", \"AddOption\", \"Product\", new { @class = \"lighb

Can anyone explain why the following happens? And how to resolve, Visual Studio 2010 and MVC2

<%= Html.Act开发者_C百科ionLink("Add New Option", "AddOption", "Product", new { @class = "lighbox" }, null)%>

Results in

/Product/AddOption?class=lightbox

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

Results in

/Product/AddOption?Length=7

Thanks


You're using these respective overloads:

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

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

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

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

The first new { @class = "lighbox" } is passed as the routeValues argument when it should be the htmlAttributes argument.

This sort of problem is common with the extension methods used in MVC. In can sometimes help to use named arguments (C# 4.0) to make things more readable:

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


This is an example of "overload hell" in ASP.NET MVC.

The first code calls the following method:

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

whereas the second code calls this one:

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

Notice that the string parameter controllerName in the first call is becoming routeValues in the second one. The string value "Product" is being passed to the routed values: the string property Length is used, which has a length of 7 here, hence the "Length=7" you're getting in the route.

Considering the first method, it seems that you've swapped the routeValues and htmlAttributes parameters.

0

精彩评论

暂无评论...
验证码 换一张
取 消