2012-05-02 23 views
0

我有一個看起來像如何在MVC3中使用多個參數生成鏈接?

public ViewResult Index(string id, string participant="", string flagged = "") 

id是我的Global.asax此控制器的路線值的控制方法。我想在其他值作爲常規參數傳遞這樣的鏈接看起來像

.../controller/Index/id?participant=yes&flagged=no 

有沒有一種方法來生成像MVC 3本使用剃刀腳本的鏈接?

回答

7

你可以通過在ActionLink的方法routeValues參數中的所有參數:

@Html.ActionLink(
    "go to index",     // linkText 
    "index",      // actionName 
    new {       // routeValues 
     id = "123", 
     participant = "yes", 
     flagged = "no" 
    } 
) 

假設默認路由設置,這將產生:

<a href="/Home/index/123?participant=yes&amp;flagged=yes">go to index</a> 

更新:

爲了進一步闡述您發佈的評論,如果ActionLink生成了一個帶有Length=6的url,這意味着您使用了錯誤的重載。例如,這是錯誤的

@Html.ActionLink(
    "go to index",    // linkText 
    "index",     // actionName 
    "home",     // routeValues 
    new {      // htmlAttributes 
     id = "123", 
     participant = "yes", 
     flagged = "no" 
    } 
) 

這是顯而易見的,爲什麼這是我沿着每個參數名稱把註釋錯誤。因此,請確保您仔細閱讀Intellisense(如果您足夠幸運,可以讓Intellisense在Razor中工作:-))選擇正確的輔助方法重載。

中要指定一個控制器名稱的情況下,正確的過載如下:

@Html.ActionLink(
    "go to index",    // linkText 
    "index",     // actionName 
    "home",     // controllerName 
    new {      // routeValues 
     id = "123", 
     participant = "yes", 
     flagged = "no" 
    }, 
    null      // htmlAttributes 
) 

注意,作爲最後一個參數傳遞的null。這對應於htmlAttributes參數。

+0

我可以發誓我已經試過這個,由於某種原因,它給了我一個長度= 6的參數,但它的工作。 –

+1

看到我的更新,我試圖進一步闡述。 –

+0

@DarinDimitrov再次回答了我的簡單問題......並給出了他的答案的細節。謝謝! – JoshYates1980

3

您可以使用此一ActionLink的:

@Html.ActionLink("Title", 
       "ActionName", 
        new {id = 1, participant = "yes", flagged = "no"}) 
相關問題