加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – asp.net mvc路由:如何使用默认动作,但非默认参

发布时间:2020-12-15 23:45:20 所属栏目:asp.Net 来源:网络整理
导读:我正在重写问题,因为迄今为止的答案告诉我,我还没有定义好它.我会留下原来的问题,以供参考. 当您设置路由时,您可以为不同的URL /路由部分指定默认值.让我们考虑VS向导生成的例子: routes.MapRoute( "Default",// Route name "{controller}/{action}/{id}",/
我正在重写问题,因为迄今为止的答案告诉我,我还没有定义好它.我会留下原来的问题,以供参考.

当您设置路由时,您可以为不同的URL /路由部分指定默认值.让我们考虑VS向导生成的例子:

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

在此示例中,如果未指定控制器,则将使用DefaultPageController,如果未指定操作,则将使用“Index”操作.
网址通常如下所示:http:// mysite / MyController / MyAction.

如果Url没有这样的操作:http:// mysite / MyController,那么将使用索引操作.

现在我们假设我的控制器Index和AnotherAction中有两个动作.对应的url分别是http:// mysite / MyController和http:// mysite / MyController / AnotherAction.我的“索引”操作接受参数id.所以如果我需要传递参数到我的索引操作,我可以这样做:http:// mysite / MyController / Index / 123.请注意,与URL http:// mysite / MyController不同,我必须明确指定Index操作.我想做的是能够通过http:// mysite / MyController / 123而不是http:// mysite / MyController / Index / 123.我不需要这个URL中的“索引”我想让mvc引擎识别,当我要求http:// mysite / MyController / 123时,123不是一个动作(因为我没有定义一个这个名字的动作),但是我的默认动作“Index”的参数.如何设置路由来实现?

以下是问题的原始措辞.

我有一个控制器,有这样的两个方法

public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(SomeFormData data)
    {
        return View();

    }

这允许我在用户导航到此URL(GET)时以及随后发布表单(POST)时,像http://网站/页面一样处理Url.

现在,当我处理这个帖子时,在某些情况下,我想将浏览器重定向到这个url:

http://website/Page/123

其中123是一些整数,我需要一个方法来处理我的控制器中的这个url.

如何设置路由,这样做有效?目前我有这样的向导生成的“默认”路由:

routes.MapRoute(
            "Default",id = UrlParameter.Optional } // Parameter defaults

我尝试添加另一个控制器方法,如下所示:

public ActionResult Index(int id)
{
    return View();
}

但是,由于引发了不明确的操作异常,这不起作用:

The current request for action ‘Index’
on controller type ‘PageController’
is ambiguous between the following
action methods:
System.Web.Mvc.ActionResult Index() on
type PageController
System.Web.Mvc.ActionResult
Index(Int32) on type PageController

我必须补充说,我也在这个控制器中有其他的动作.如果没有,This会工作.

解决方法

这是如何解决的:

您可以创建一个路由约束,以指示路由引擎,如果您有一些url中的东西看起来像一个数字(123),那么这是一个默认操作的操作参数,如果你有一些不像number(AnotherAction)然后它是一个动作.

考虑这个代码:

routes.MapRoute(
  "MyController","MyController/{productId}",new {controller="My",action="Index"},new {productId = @"d+" });

此路由定义将只匹配MyController在http:// mysite / MyController / 123中的数值,因此它不会干扰在同一个控制器上调用另一个操作.

资料来源:Creating a Route Constraint

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读