2017-06-09 40 views
1

在我的MVC5應用程序中,我試圖將一個字符串傳遞給一個動作。爲什麼不將字符串參數路由到動作?

PodcastsController我有一個動作叫Tagged

public ActionResult Tagged(string tag) 
{ 
    return View(); 
} 

例如,如果我想要的字符串Test傳遞給Tagged行動,它看起來像這樣的網址:

/播客/標記/測試

我有一個這樣的路線:

routes.MapRoute(
     "Podcasts", 
     "Podcasts/Tagged/{tag}", 
     new { controller = "Podcasts", action = "Tagged", tag = UrlParameter.Optional } 
    ); 

編輯我打電話了Tagged動作是這樣的:

if (!string.IsNullOrEmpty(tagSlug)) 
{ 
    return RedirectToAction("Tagged", "Podcasts", new { tag = tagSlug }); 
} 

當我設置一個破發點上Tagged行動,tag總是空

任何人都可以看到我做錯了什麼?

我敢肯定有一些錯誤的路線,但我想不出什麼...

+0

@maccettura,我是一個相對較新的程序員 - 你能解釋一下嗎? –

+0

你可以分享你調用'標記'行動的代碼嗎? –

+0

@VinylWarmth我最初誤讀你的文章。忽略我以前的評論。當你點擊路線時,你是否能夠在你的「標記」行動中找到斷點? – maccettura

回答

1

你得到一個null的原因是因爲你實際上沒有在你的代碼中傳入一個叫做tag的參數:

if (!string.IsNullOrEmpty(tagSlug)) 
{ 
    return RedirectToAction("Tagged", "Podcasts", new { tagSlug }); 
} 

當你忽略它需要變量名的屬性名,所以你實際上是傳遞變量tagSlug,你的行動不接受。試試這個:

if (!string.IsNullOrEmpty(tagSlug)) 
{ 
    return RedirectToAction("Tagged", "Podcasts", new { tag = tagSlug }); 
} 
+0

我編輯了我的帖子,那是我的一個錯字。 –

+0

所以你有一個名爲'tag'的變量,你通過了嗎?我們可以看到標籤被定義在哪裏嗎? – maccettura

+1

請忽略我的第一條評論,這解決了我的問題! –

0

必須exacly這樣的工作....

然後去http://localhost:64147/podcast/tagged/hi和recive喜如標籤

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     name: "MyRoute", 
     url: "podcast/tagged/{tag}", 
     defaults: new { controller = "Podcasts", action = "Tagged", tag = UrlParameter.Optional } 
    ); 

    routes.MapRoute(
     name: "Default", 
     url: "{controller}/{action}/{id}", 
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
} 
0

的價值我很抱歉,我要問在這裏,但你檢查你的路線之前,可以覆蓋任何其他途徑?

路由是按照順序完成的。對應於給定參數的第一路由選擇,所以如果你有這樣的路線第一

{controller}/{action}/{id} 

然後

Podcasts/Tagged/{tag} 

,因爲第一個路徑選擇

路線順序,你會得到空其實很重要

+0

嗨,我的帖子中的動作是第一個路線和默認操作是最後一個。 –

相關問題