public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Letter",
url: "{Home}/{Letter}/{ListId}",
defaults: new { controller = "Home", action = "Letter", ListId=1}
);
routes.MapRoute(
name: "words",
url: "{Home}/{words}/{WListId}",
defaults: new { controller = "Home", action = "words", WListId ="w1" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id= UrlParameter.Optional }
);
}
CSHTML:
@Html.ActionLink("Home", "Index", "Home")
@Html.ActionLink("Letter", "Letter/1", "Home")
@Html.ActionLink("Words", "words/w1", "Home")
我分别在route.config
和.cshtml
中执行此操作,但每次将其重定向到信函页面时,即使我点击“字词”或“主页”。当我单击单词或主页时,它会更改网址但不会更改视图。任何人都可以建议如何在route.config文件中给出倍数路由?这段代码出了什么问题?
答案 0 :(得分:1)
我正在彻底改进这个,因为我觉得我现在看到你想要做的事情。
ActionLink
用作渲染锚元素的助手。所以使用
@Html.ActionLink("Link", "Action", "Controller")
帮助,您的页面呈现以下形式的内容:
<a href="/Controller/Action">Link</a>
你想要的是写出正确的控制器和动作值 - 你不需要这样的路线。因此,为了生成Home/words/1
的链接,您可以使用ActionLink
帮助程序(仅限默认路由),如下所示:
@Html.ActionLink("Words", "Words", "Home", new { WListId = "w1" })
这将产生:
/Home/Words/w1
并在您的HomeController.cs
中,您的操作必须如下:
public ActionResult Words(string WListId)
{
// whatever you want to do with WListId
return View();
}
并且您的视图必须命名为Words.cshtml
同样适用于Letter。为此,您只需要一条已经存在的默认路线。
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id=UrlParameter.Optional });