开发者

QueryString id parameter not being used

I've got a very basic ASP.Net MVC project where I'd like to use a parameter name of id on one of my controller actions. From everything I've read that shouldn't be a problem but for some reason using a parameter name of id fails to get the value extracted from the query string but if I change it to any other different name it will work.

I only have a single route in my global.asx

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

My controller method is:

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

A URL of http://mysite/customer/confirm/abcd works. A URL of http://mysite/customer/confirm?id=abcd fails.

If I change the controller method to:

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

then a URL of http://mysite/customer/confirm?customerID=abcd works.

Is there something special about using "id" as a parameter in an ASP.Net MVC query string?

Update: Changed id from 1234 to abcd, my id's are actually strings.


If you do not apply an id parameter (either querystring or POST), the system just ignores it, and you can remove the "id" parameter in your controller:

public ActionResult Confirm()

In your case, you would just stick with the id parameter. Why make an ugly customerID parameter, when id is "mapped" automatically?

This is an easy and simple example of the use of id parameter.

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();
}

This works too, for me. We're doing it in our application right now with a standard route:

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();
}


If you need to have id in query string, then don't create route with 'id' parameter. In case you have route "{controller}/{action}" then you can use public ActionResult Confirm(string id) as your controller method.

Routes don't care about query strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜