【发布时间】:2018-02-07 20:35:26
【问题描述】:
在 MVC 中,我试图从一个 ActionResult 方法传递一个可选的 ID 参数,并且我想在另一个 ActionResult 方法中捕获该 ID。我目前有以下代码,但我仍然找不到在Method2() 中获取 ID 的方法。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Method1(SomeModel model)
{
int someID = model.something.Id;
.
..
...
return RedirectToAction("Method2", new { userID = someID});
}
单击 Method1 的 View 页面上的按钮后,代码将引导我进入 Method2 页面,我会在我的 URL 中看到类似的内容
http://localhost:1234/myController/method2?userid=100 请注意,?userid=100 在调用 Method2 时已成功传递到 URL。
这是我的方法 2。我正在尝试获取userid,但我不能。
[HttpGet]
public ActionResult Method2()
{
**I want to get the userID from the URL**
}
我什至尝试使用int? id,但我的 id 仍然为空。
public ActionResult Method2(int? id)
{
//id return null all the time
}
对我如何在 Method2() 的 URL 中获取 userid 有任何帮助吗?
【问题讨论】:
-
使用 ActionResult Method2() 中的 Request.QueryString 键值对集合来获取用户 ID
-
将
userId添加到方法签名中。public ActionResult Method2(int? userID). -
如果方法为
public ActionResult Method2(int? id),则直接使用new { id= someID }(参数名称必须匹配) -
我明白我做错了什么。我没有使用匹配的参数名称。谢谢
标签: asp.net-mvc