未使用 QueryString id 参数

2024-04-17

我有一个非常基本的 ASP.Net MVC 项目,我想在我的控制器操作之一上使用 id 参数名称。从我读过的所有内容来看,这应该不是问题,但由于某种原因,使用 id 参数名称无法获取从查询字符串中提取的值,但如果我将其更改为任何其他不同的名称,它将起作用。

我的 global.asx 中只有一条路线

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

我的控制器方法是:

public ActionResult Confirm(string id)
{
     ....
}

网址为http://mysite/customer/confirm/abcd http://mysite/customer/confirm/abcd作品。网址为http://mysite/customer/confirm?id=abcd http://mysite/customer/confirm?id=abcd fails.

如果我将控制器方法更改为:

public ActionResult Confirm(string customerID)
{
     ....
}

然后是一个 URLhttp://mysite/customer/confirm?customerID=abcd http://mysite/customer/confirm?customerID=abcd works.

在 ASP.Net MVC 查询字符串中使用“id”作为参数有什么特别之处吗?

更新:将 id 从 1234 更改为 abcd,我的 id 实际上是字符串。


如果您不应用 id 参数(查询字符串或 POST),系统只会忽略它,您可以在控制器中删除“id”参数:

public ActionResult Confirm()

在您的情况下,您只需使用 id 参数即可。当 id 自动“映射”时,为什么要创建一个丑陋的 customerID 参数?

这是一个使用 id 参数的简单示例。

public ActionResult Confirm(int? id)
{
     if (id.HasValue && id.Value > 0) // check the id is actually a valid int
         _customerServer.GetById(id.Value);

    // do something with the customer

    return View();
}

这对我来说也有效。我们现在正在我们的应用程序中使用标准路线来执行此操作:

public ActionResult Confirm(string id)
{
     if (!string.IsNullOrEmpty(id)) // check the id is actually a valid string
         _customerServer.GetByStringId(id);

    // do something with the customer

    return View();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

未使用 QueryString id 参数 的相关文章

随机推荐