RouteLink空Href

时间:2011-07-02 16:05:07

标签: asp.net-mvc-3 routelink

我正在使用MVC3和Razor View Engine。我想为Href使用某个Route

以下是路线注册,(路线似乎工作,因为我可以使用浏览器直接使用它)

routes.MapRoute(
    "AddItem",
    "{listAreaName}/{listSlug}/Add",
    new { controller = "List", action = "AddItem" }
    );

但@ Html.RouteLink不起作用。它为链接返回一个空的href

以下是我的一些尝试

@Html.RouteLink("Add New Item", "AddItem", new { controller="List", action="AddItem", listAreaName = Model.ListAreaName, listSlug = Model.Slug })<br />
@Html.RouteLink("Add New Item1", "AddItem", new { controller = "List", listAreaName = Model.ListAreaName, listSlug = Model.Slug })<br />
@Html.RouteLink("Add New Item2", "AddItem", new { action = "AddItem", listAreaName = Model.ListAreaName, listSlug = Model.Slug })<br />
@Html.RouteLink("Add New Item3", "AddItem", new { controller = "list", action = "additem", listAreaName = Model.ListAreaName, listSlug = Model.Slug })<br />
@Html.RouteLink("Add New Item4", "additem", new { controller = "List", action = "AddItem", listAreaName = Model.ListAreaName, listSlug = Model.Slug })<br />

@Html.RouteLink("Add New Item5", "additem", new { listAreaName = Model.ListAreaName, listSlug = Model.Slug })<br />
@Html.RouteLink("Add New Item6", "AddItem", new { controller = "ListController", action = "AddItem", listAreaName = Model.ListAreaName, listSlug = Model.Slug })<br />

如果我错过了路线名称,它会生成工作链接,但它的格式不正确

我发现的大多数材料都是v1的预览版。这个问题有待分类吗?

任何想法?

2 个答案:

答案 0 :(得分:2)

在最后一个路线链接中你有一个错误,你不应该使用Controller后缀:

@Html.RouteLink(
    "Add New Item6", 
    "AddItem", 
    new { 
        controller = "List", 
        action = "AddItem", 
        listAreaName = Model.ListAreaName, 
        listSlug = Model.Slug 
    }
)

就其他人而言,他们都会在ASP.NET MVC 3 RTM中生成以下URL:/ListAreaName/Slug/Add,假设您已设置默认路由,并且已添加了问题中显示的路由。

答案 1 :(得分:1)

修改

路线中只有一个元素可以省略默认值。您没有listAreaName或listSlug的默认值。请参阅此问题:asp mvc routing with two optional parameters

routes.MapRoute(
    "AddItem",
    "{listAreaName}/{listSlug}/Add",
    new
    {
        controller = "List",
        action = "AddItem",
        listAreaName = "foo", // <-- add these
        listSlug = UrlParameter.Optional
    });

<强>原始

您的路线实际上并不包含控制器和操作参数。您是否尝试从路由值中省略它们(当在请求中解码路由时将推断它们)。我要做的另一件事是确保模型实际包含ListAreaNameSlug值。

@Html.RouteLink("Add New Item",
                "AddItem",
                new
                {
                     listAreaName = Model.ListAreaName,
                     listSlug = Model.Slug 
                })<br />

另外,你真的应该使用CSS来设置它们作为块级元素的样式,而不是在它之后添加<br/>,如果可能的话。

<style>
   .block { display: block; }
</style>

@Html.RouteLink("Add New Item",
                "AddItem",
                new
                {
                     listAreaName = Model.ListAreaName,
                     listSlug = Model.Slug 
                },
                new { @class = "block" })