MVC 中的参数未从路由正确传递到视图中

Parameters in MVC not being correctly passed into the view from routing

我正在自学 MVC,但在正确路由方面遇到了问题

我有一个名为 "ClipsController" 的控制器和 1 个名为 "Index" 的视图(无聊,我知道)

我的 routeconfig 文件配置了以下路由:

routes.MapRoute(
    "Clips",
    "Clips/{id}",
    new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);

"Default" 路线之前。当我去 /Clips/ExampleID 它确实击中了正确的路线,并且确实在 Clips 控制器中启动了 Index 操作。我遇到的问题是参数 'ID' 无法传递到索引页面,但我最终进入了 Clips 控制器的索引操作,URL domain.my/Clips/ExampleID

我尝试使用

获取 ID 参数
httpcontext.current.request.querystring["id"]

始终 returns 为空。我在controller中的actionresult如下:

public ActionResult Index(string id)
{
    return view()
}

重申一下,我无法在索引视图中看到查询字符串 ID,即使 URL 执行了正确的路由,并且控制器中的 actionresult 对我来说是正确的。如果我做错了什么或者您需要更多信息,请告诉我,谢谢。

I attempt to get the ID parameter with

httpcontext.current.request.querystring["id"]

不,您在此 url:

中没有任何查询字符串参数
http://domain.my/Clips/ExampleID

查询字符串参数跟在 url 中的 ? 字符之后。例如,如果您有以下 url:

http://domain.my/Clips?id=ExampleID

然后您可以尝试使用您的初始代码读取 id 查询字符串参数。

用这个 url: http://domain.my/Clips/ExampleID 你可以查询 id 路由值参数。但是使用 HttpContext.Current 绝对是错误的做法。您永远不应在 ASP.NET MVC 应用程序中使用 HttpContext.Current。恰恰相反,您可以在任何可以访问 HttpContextBase 的地方访问此信息(在 ASP.NET MVC 应用程序管道中几乎无处不在):

httpContext.Request.RequestContext.RouteData.Values["id"]

长话短说,如果您需要在控制器操作中查询此参数的值,您只需使用提供的 id 参数:

public ActionResult Index(string id)
{
    // Here the id argument will map to ExampleID
    return view()
}

此外,您可能不需要您的自定义路线:

routes.MapRoute(
    "Clips",
    "Clips/{id}",
    new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);

这完全是多余的,它已经被默认路由覆盖了:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

所以请随意摆脱您的自定义路线。