URL.Action包括ID构造URL时, [英] URL.Action includes id when constructing URL

查看:388
本文介绍了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时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆