URL.Action包括ID构造URL时,

编程入门 行业动态 更新时间:2024-10-25 16:20:17
本文介绍了URL.Action包括ID构造URL时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用ASP.Net MVC。这里是我的code段从控制器命名的课程:

I'm using ASP.Net MVC. Here's my code snippets from a controller named Course:

public ActionResult List(int id) { var viewmodel.ShowUrl = Url.Action("Show", "Course"); ... } public ActionResult Show(int id) { ... }

viewmodel.ShowUrl拾取任何的值是ID参数。所以viewmodel.ShowUrl变为/场/显示/ 151(ID值是151);我希望能够以设置基于用户交互的客户端上的ID部分。我想viewmodel.ShowUrl的值为/场/展。

viewmodel.ShowUrl picks up whatever the value is of the "id" parameter. So viewmodel.ShowUrl becomes "/Course/Show/151" (value of id is 151); I want to be able to set the id part on the client based on user interaction. I want the value of viewmodel.ShowUrl to be "/Course/Show".

这似乎是我的错误。我不会告诉Url.Action包括id值。它做它自身。如果我想设置id的值,然后我会做这样的事情:

This seems like a bug to me. I'm not telling Url.Action to include an id value. It's doing it on its own. If I want to set the id value then I would do something like this:

var viewmodel.ShowUrl = Url.Action("Show", "Course", new {id = somevalue});

那么,你怎么了prevent MVC从增加的id值?我可以硬code viewmodel.ShowUrl为/场/显示,但似乎是一个缺憾的解决方案。谢谢你。

So, how do you prevent MVC from adding the id value? I can hardcode viewmodel.ShowUrl to "/Course/Show" but that seems to be a kludgy solution. Thanks.

推荐答案

我猜你的路由,你不指定id是一个可选的参数。下面是一个示例项目的默认路由。

I'm guessing in your routing, you're not specifying that id is an optional parameter. Here's the default route in a sample project.

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

请注意 ID = UrlParameter.Optional 列入。如果没有,你会得到,因为它认为该ID是强制性您所描述的行为。

Note the inclusion of id = UrlParameter.Optional. Without that, you'd get the behavior you're describing because it thinks the id is mandatory.

在一个侧面说明,如果你的显示操作并不总是有一个id那么它应该是可为空或提供一个默认的。

On a side note, if your Show action doesn't always have an id then it should be nullable or provide a default.

public ActionResult Show(int? id) public ActionResult Show(int id = 0)

否则,你就当你尝试加载的网址没有id参数得到一个错误。

Otherwise you'll get an error when you try loading the url without the id parameter.

更多推荐

URL.Action包括ID构造URL时,

本文发布于:2023-11-03 20:39:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556038.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:URL   Action   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!