2013-03-11 113 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(); 
}