gpt4 book ai didi

c# - ASP.NET MVC 不同的路由用于不同的 Action

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:36 24 4
gpt4 key购买 nike

我正在使用 ASP.NET MVC 构建站点。在RouteConfig中,我修改了这样的方法:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{Director}/{Movie}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional, Director = UrlParameter.Optional, Movie = UrlParameter.Optional }
);

routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Movies", action = "Create", id = UrlParameter.Optional }
);
}

在 IndexView 中,我编码如下:

@model IEnumerable<MvcMovie.Models.Director>

<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
<tr>
<td>
@foreach (var movie in item.Movies)
{
<div style="width: 100%;">
@Html.ActionLink(movie.Title, "Index", new { Director = movie.Director.Name, Movie = movie.Title }, null)
</div>
}
</td>
</tr>
}
</table>

实际上,我修改了 RouteConfig,因为我想要不同的导演和不同的电影使用不同的 URL,以满足我们客户的 SEO 要求

对于 Index 操作,它工作正常,但即使我尝试使用 @Html.ActionLink("Create New", "Create "),它仍然调用 Index 操作。据我目前的理解,它应该调用 Create Action 。我是 MVC 的新手,如果我的问题看起来很愚蠢,我很抱歉。但是我在这里缺少什么重要的东西?

最佳答案

Routeconfig 自上而下检查。

更新:您应该在路由中指定 Controller 名称,否则您的路由配置在您的问题中的方式,Default2 永远不会被解雇。有 2 条路由以 {something} 开头意味着第二条不会被解雇。我猜您希望您的 URL 是 localhost/movies/create/id。为此,请执行以下操作:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "MoviesDefault",
url: "Movies/{action}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional }
);

/* not sure about this route without testing -
/* i think it would conflict with the above route
routes.MapRoute(
name: "MovieDirector",
url: "Movies/{Director}/{Movie}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional, Director = UrlParameter.Optional, Movie = UrlParameter.Optional }
);
*/

// for this following route, i've left 'Movies' as the controller, but it should be
// your 'home page' controller. As in, whatever your default http://localhost:port/ should be.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional }
);
}

关于c# - ASP.NET MVC 不同的路由用于不同的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17161411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com