gpt4 book ai didi

asp.net-mvc - 为什么需要为 Html.Action 定义路由?

转载 作者:行者123 更新时间:2023-12-04 08:37:14 25 4
gpt4 key购买 nike

我创建了一个带有 2 个 Controller 的空 ASP.NET MVC 3 应用程序,HomeControllerOtherController .

HomeController.cs 看起来像这样:

public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}

Index.cshtml 看起来像这样:
@Html.Action("Index", "Other")

当然还有 Othercontroller.cs:
public class OtherController : Controller
{
[ChildActionOnly]
public ActionResult Index()
{
return Content("OK!");
}
}

到现在为止还挺好。我运行应用程序,它告诉我一切都是 OK!
现在,我采用默认 RegisterRoutes来自 Global.asax.cs:
    public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}

我把它弄皱了,所以没有路线匹配 OtherController :
    public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute("Default", "", new { controller = "Home", action = "Index" });
}

现在,当我运行该页面时,它会崩溃并显示以下错误消息:
 System.InvalidOperationException: No route in the route table matches the supplied values.
Source Error:
Line 1: @Html.Action("Index", "Other")

我在对 .Action 的调用中指定了 Controller 名称和操作名称.没有生成任何 URL,也没有发出请求。 为什么路由甚至需要参与?

最佳答案

我认为这篇博文将帮助您了解更多:

http://blogs.charteris.com/blogs/gopalk/archive/2009/01/20/how-does-asp-net-mvc-work.aspx .

本质上,路由涉及根据您发送的参数确定要“启动”哪个 Controller 来处理请求以及要调用的适当操作,并且 MVCRouteHandler 使用这些参数来做出决定。仅仅因为你告诉它在你的操作中哪个 Controller 不会让它神奇地忽略路由表,直接进入那个 Controller 类并绕过后端发生的所有其他 MVC 优点。请记住,这些 @HTML.Action方法可以承受大量的重载,这些重载可能会影响路由表中要使用的路由(例如考虑 URL 结构)。

MVC 路径不是静态内容,因此必须通过 URLRoutingModule 解析,该模块使用路由表来决定要做什么。由于您没有匹配的路线 - 您会收到错误消息。

编辑

在我的谩骂中,我实际上并没有谈到你的最后陈述。没错,没有生成 URL,但生成了对应用程序的请求。 HTML.Action 仍然会使用路由来决定使用什么 Controller 、 Action 、区域、参数。我认为用简单的话来说这就像生成一个 ActionLink 并为您单击它是公平的。

关于asp.net-mvc - 为什么需要为 Html.Action 定义路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8935750/

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