我正在使用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的预览版。这个问题有待分类吗?
任何想法?
答案 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
});
<强>原始强>
您的路线实际上并不包含控制器和操作参数。您是否尝试从路由值中省略它们(当在请求中解码路由时将推断它们)。我要做的另一件事是确保模型实际包含ListAreaName
和Slug
值。
@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" })