如何将路由操作作为参数传递给具有MVC4的Index方法



我有以下路由,任何以A、F或L开头的URL都指向该路由到索引操作。它看起来像是使用了一个C语言的正则表达式。

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

我想做一些类似的事情,但这次指示任何具有菜单、目标、页面或主题操作的URL转到索引操作,并将单词"菜单"、"目标"、"页面"或"主题"作为参数传递到索引操作:

有人能教我怎么做吗。它看起来像一个C#类型的正则表达式,但是我不确定如何执行第二个所需的表达式路线

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

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

然后你的动作方法签名会像这样:

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

看看这个例子。。。

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作为参数处理

编辑了答案:Regex中的b查找单词边界。。。还没有测试过,但应该有效。。。http://www.regular-expressions.info/wordboundaries.htmlhttp://www.regular-expressions.info/alternation.html

最新更新