Reputation:
This is my default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
And I want to be able to get the id
parameter.
This is controller:
public ActionResult Index(int page = 1)
{
var cars = repositoryManager.CarRepository.GetAll().Skip(page).Take(1).ToList();
return View(cars);
}
The thing is when I enter:
/home/index/5
page
is still 1
. Why? I extected page
is 1
only when it is default parameter.
Upvotes: 0
Views: 2925
Reputation: 56909
Action parameters are passed into the action method by Value Providers. These providers work by supplying the action method parameters when the key (the name of the parameter) matches a key in the value source. There are value providers for both route values and for query strings, but regardless of where they pull the data from the key passed in must match the key of the data source.
The keys that are defined in your default route for route values are controller
, action
, and id
:
url: "{controller}/{action}/{id}"
However, the key that you defined in your action method is page
:
public ActionResult Index(int page = 1)
Since there are no keys in that source named page
, no value will be passed into your action method from route values, and it will continue trying other sources such as the query string. If no value named page
is found in any of the value providers, the value will be empty and thus your default action method value will be used.
The simplest fix is to rename the key in your action method to id
:
public ActionResult Index(int id = 1)
Alternatively, create a specialized route and pass the key through as page
instead of id
:
routes.MapRoute(
name: "DefaultWithPage",
url: "Home/Index/{page}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Upvotes: 0
Reputation: 15015
The page
is 1 because your are passing id
as 5 not page
, so page
would get its default value which is 1.
If you change name of page
to id
your code works, but it's not a good naming!
public ActionResult Index(int id = 1)
{
var cars = repositoryManager.CarRepository.GetAll().Skip(id).Take(1).ToList();
return View(cars);
}
You can also send page
as query string /home/index?page=5
Upvotes: 1