我正在自学 MVC,但在正确路由方面遇到问题
我有一个名为“ClipsController”的 Controller 和 1 个名为“Index”的 View (我知道很无聊)
我的路由配置文件配置了以下路由:
routes.MapRoute(
"Clips",
"Clips/{id}",
new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);
这是“默认”路线之前。当我转到/Clips/ExampleID 时 它确实到达了正确的路线,并且在剪辑 Controller 中启动了索引操作。我遇到的问题是参数“ID”无法传递到索引页面,但我最终执行了 Clips Controller 的索引操作,URL 为domain.my/Clips/ExampleID
我尝试使用
获取 ID 参数httpcontext.current.request.querystring["id"]
总是返回 null。我在 Controller 中的操作结果如下:
public ActionResult Index(string id)
{
return view()
}
重申一下,即使 URL 执行了正确的路由,并且 Controller 中的操作结果据我所知是正确的,我也无法在索引 View 上看到查询字符串 id。如果我做错了什么或者您需要更多信息,请告诉我,谢谢。
最佳答案
I attempt to get the ID parameter with
httpcontext.current.request.querystring["id"]
不,此网址中没有任何查询字符串参数:
http://domain.my/Clips/ExampleID
查询字符串参数位于 URL 中的 ?
字符之后。例如,如果您有以下网址:
http://domain.my/Clips?id=ExampleID
然后您可以尝试使用初始代码读取 id
查询字符串参数。
使用此网址:http://domain.my/Clips/ExampleID
,您可以查询id
路由值参数。但使用 HttpContext.Current 绝对是错误的方法。切勿在 ASP.NET MVC 应用程序中使用 HttpContext.Current。恰恰相反,您可以在任何可以访问 HttpContextBase
的地方访问此信息(ASP.NET MVC 应用程序管道中几乎无处不在):
httpContext.Request.RequestContext.RouteData.Values["id"]
长话短说,如果您需要在 Controller 操作中查询此参数的值,您只需使用提供的 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 }
);
因此,您可以随意摆脱您的自定义路线。
关于c# - MVC 中的参数未从路由正确传递到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34600283/