簡體   English   中英

如何使用MVC4將路由操作作為參數傳遞給Index方法

[英]How can I pass a route action as a parameter to an Index method with MVC4

我有以下路線,其中任何以A,F或L開頭的URL都將定向到Index操作。 看起來好像使用了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"}

);

假設您有一個帶有Index操作的ContentController,該操作將TypeOfAction作為參數處理

編輯答案:正則表達式中的\\b發現單詞邊界...尚未測試,但應該可以使用... http://www.regular-expressions.info/wordboundaries.html http://www.regular-expressions。 info / alternation.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM