ASP.NET MVC Actionlink返回空链接

时间:2012-09-14 13:14:59

标签: asp.net-mvc asp.net-mvc-routing actionlink

我遇到了这个问题并搜索了Google和StackOverflow,但似乎我找不到适合它的解决方案。

我在Global.asax.cs中映射了以下路由

 routes.MapRoute(
       "posRoute", // Route name
       "pos/{guid}", // URL with parameters
       new { controller = "Pos", action = "Index", guid = UrlParameter.Optional } // Parameter defaults
 );

 routes.MapRoute(
       "foxRoute", // Route name
       "fox/{guid}", // URL with parameters
       new { controller = "Fox", action = "Index", guid = UrlParameter.Optional } // Parameter defaults
        );

我想与HTML帮助程序Actionlink建立链接,但它一直返回一个空链接。

@Html.ActionLink("Proceed", "device")

返回

<a href="">Proceed</a>


@Html.ActionLink("Proceed", "device", "Fox" , new { guid = "test" })

返回

<a href="" guid="test">Proceed</a>

预期结果如下:

<a href="/fox/index/test">Proceed</a>

或更好

<a href="/fox/test">Proceed</a>

1 个答案:

答案 0 :(得分:1)

尝试this重载。

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

所以你的代码将是

@Html.ActionLink("Proceed", "device", "Fox" , new { guid = "test" },null)

如果要传递任何HTML属性,例如 CSS class / ID of element ,您可以将最后一个参数calue(在我们的例子中为null)替换为。

还要确保在特定路线下方具有通用路线定义

routes.MapRoute(
            "posRoute", 
            "pos/{guid}", 
            new { controller = "Pos", action = "Index", 
            guid = UrlParameter.Optional } // Parameter defaults
        );

routes.MapRoute(
            "foxRoute", // Route name
            "fox/{guid}", // URL with parameters
            new { controller = "Fox", action = "Index",
            guid = UrlParameter.Optional } // Parameter defaults
        );

routes.MapRoute("Default","{controller}/{action}/{id}",
          new { controller = "Home", action = "Index",
                    id = UrlParameter.Optional })