在我的索引页面中,我正在使用以下内容生成 url
@foreach(var c in ViewBag.cities)
{
<li>@Html.ActionLink((string)c.CityName,"somepage",new{city=c.CityName, id=c.Id})</li>
}
它为每个城市生成以下格式的网址
localhost:55055/1/city1
localhost:55055/2/city2
...
其中 1,2 是 Id 和 city1, city2 是 CityName
我已将路线配置为
routes.MapRoute(
name: "CityRoute",
url: "{id}/{city}",
defaults: new { controller = "Home", action = "somepage", id = UrlParameter.Optional, city = UrlParameter.Optional }
);
Home Controller中的somepage
action方法:
public string somepage(int id, string city)
{
return city + " " + id;
}
即使我试过这个
public string somepage()
{
return "Hello";
}
但它导致Resource cannot be found
我尝试在其中放置sompage
永远不会被击中的断点。
任何建议
更新
正如@KD 在下面的评论中指出的那样,我更改了路线顺序并将上述规则置于所有规则之上。我也改变了方法
public ActionResult somepage(int id=0, string city="")
{
return Content(city + " " + id);
}
现在行为改变了,默认规则
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
不用于普通索引页。相反,使用这种用法是因为方法中的断点somepage
被命中,如果我把它放在http://localhost:55055/2/cityname
浏览器中,页面会显示 id 和 cityname。但是现在默认路由不用于应用程序主页http://localhost:55055/