【问题标题】:How can I pass a route action as a parameter to an Index method with MVC4如何使用 MVC4 将路由操作作为参数传递给 Index 方法
【发布时间】:2012-09-06 12:40:32
【问题描述】:

我有以下路线,其中指向以 A、F 或 L 开头的任何 URL 到索引操作。好像使用了升 C 正则表达式。

        context.MapRoute(
            "content",
            "{page}/{title}",
            new { controller = "Server", action = "Index" },
            new { page = @"^[AFL][0-9A-Z]{3}$" }
        );

我想做类似的事情,但这次将任何具有菜单、目标、页面或主题操作的 URL 引导到索引操作并传递“菜单”、“目标”、“页面”或“主题”以 Index 动作作为参数:

谁能告诉我如何做到这一点。它看起来像一种 C# 正则表达式,但我不知道如何做第二个我需要的表达式 路线。

【问题讨论】:

  • 它看起来像一个升 C 正则表达式。这告诉我您在询问之前没有查看文档...

标签: c# asp.net-mvc asp.net-mvc-3 routes


【解决方案1】:

你只需要一个简单的路由约束:

   context.MapRoute(
        "content",
        "{page}/{title}",
        new { controller = "Server", action = "Index" },
        new { page = @"Menus|Objectives|Pages|Topics" }
    );

然后您的操作方法签名将如下所示:

public ActionResult Index(string page)
{
    ...
    return View();
}

【讨论】:

    【解决方案2】:

    看看这个例子……

    http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs 你已经定义了一个带参数的路由。

    routes.MapRoute(
        "Content",
        "Content/{TypeOfAction}",
        new {controller="Content", action="Index"},
        new {@"\b(Menus|Objectives|Pages|Topics)\b"}
    
    );
    

    假设您有一个 ContentController,其中包含一个 Index 操作,它将 TypeOfAction 作为参数处理

    编辑了答案: \b 在正则表达式中找到单词边界...尚未对其进行测试,但应该可以... http://www.regular-expressions.info/wordboundaries.html http://www.regular-expressions.info/alternation.html

    【讨论】:

    • 但是您提供的路线将允许 TypeOfAction 中的任何内容。我需要的只是那些有问题的人。
    • 已编辑答案...语法超出了我的想象,因此您可能需要稍微调整一下... /b 通过正则表达式查找单词边界
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多