【问题标题】:retrieve the ID parameter from url从 url 检索 ID 参数
【发布时间】: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


【解决方案1】:

您的查询字符串的变量名和 actionresult 变量名必须匹配

[HttpGet]
public ActionResult Method2(int userid)
{
    //your code        
}

甚至

public ActionResult Method2(int? userid)
{
    //id return null all the time
}

【讨论】:

    【解决方案2】:

    userid 的值键值对在请求查询字符串集合中。要获得它,请执行以下操作:

    if (Request.QueryString.Count > 0)
    {
        if(Request.QueryString["userid"] != null)
        {
             int userId = (int)Request.QueryString["userid"];
        }
    }
    

    【讨论】:

    • 你为什么这么辛苦?不要用你有刀的斧头切苹果
    • 我不相信我发布的内容有任何难度,实际上它显示了完成他正在尝试做的事情的另一种方式。
    • 他把查询字符串变量名弄乱了
    • 是的,他做到了。你的方法行得通,但我的建议也行。
    • 我已经使用了我在自己的开发中发布的内容,我可以向您保证它确实有效。
    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多