2013-03-11 85 views
0

如何從參數中獲取值?我有鏈接:
1)http://localhost:2409/Account/Confirmation/16
2)../Account/Confirmation/12ds-2saa-fcse
我想在控制器方法中獲得「16」或「12ds-2saa-fcse」。

從參數MVC獲取值

我的方法

public ActionResult Confirmation(int id) 
    { 
     ViewBag.Message = "ID is: " + id; 
     return View(); 
    } 

但它返回null。

路線:

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

我怎樣才能做到這一點?

編輯!

一切正常perfercly,我不知道爲什麼,但重新啓動VS2012幫助..:o

現在是另一個問題。有沒有可能通過此鏈接獲得hash值? /Account/Confirmation/16?hash=dasdsadasda。下面的代碼並不顯示哈希串..

public ActionResult Confirmation(int id, string hash) 
    { 
     ViewBag.Message = "ID is: " + id + HttpUtility.HtmlEncode("hash"); 
     return View(); 
    } 
+0

看看編輯後 – whoah 2013-03-11 22:37:14

+0

這取決於你的路由配置,是什麼樣子?另外,一個'int'參數永遠不會爲空,所以當你這樣說的時候你的意思是什麼? – roryf 2013-03-11 22:38:09

+0

您使用哪條路線?只是默認,或任何自定義路線? – 2013-03-11 22:38:13

回答

1

你更新的問題是,你是編碼字符串"hash";而不是字符串變量hash的值。

此:

public ActionResult Confirmation(int id, string hash) 
{ 
    ViewBag.Message = "ID is: " + id + HttpUtility.HtmlEncode("hash"); 
    return View(); 
} 

應該成爲這樣的:

public ActionResult Confirmation(int id, string hash) 
{ 
    ViewBag.Message = "ID is: " + id + HttpUtility.HtmlEncode(hash); 
    return View(); 
}