I have creating URL using RouteLink.
@Html.RouteLink("Edit", "PageWithId",
new
{
controller = "Customers",
action = "Edit",
id = item.CustomerID,
page = ViewBag.CurrentPage
})
I am using this routing PageWithId with route link
routes.MapRoute(
name: "PageWithId",
url: "{controller}/{action}/{page}/{id}",
defaults: new { controller = "Customers", action = "Edit", page = UrlParameter.Optional, id = UrlParameter.Optional }
);
I have 3 routing code. Here is all
routes.MapRoute(
name: "PageWithSort",
url: "{controller}/{action}/{page}/{SortColumn}/{CurrentSort}",
defaults: new { action = "Index", page = UrlParameter.Optional, SortColumn = UrlParameter.Optional, CurrentSort = UrlParameter.Optional }
);
routes.MapRoute(
name: "PageWithId",
url: "{controller}/{action}/{page}/{id}",
defaults: new { controller = "Customers", action = "Edit", page = UrlParameter.Optional, id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
When I run my program the route link generate URL like http://localhost:55831/Customers/Edit/1/ALFKI
When I click on the link the Edit action is getting called but customer id is getting null where as ALFKI is there in URL as customer id.
Here is my edit action details
public ActionResult Edit(string id, int page)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
ViewBag.CurrentPage = page;
return View(customer);
}
Please tell me why id is getting null when ALFKI as passing as customer id?
The first route
PageWithSortis applied instead of the second one.Note that the routing framework does not know which parameter name you used to generate the URL. It just looks at the received string
Customers/Edit/1/ALFKI.For this string, the first route "PageWithSort" matches with
Because the first matching route will be used, this URL will never hit the "PageWithId" route.
Maybe you can make the
SortColumnandCurrentSortparameters of "PageWithSort" required?Or change the order in which the routes are defined.
Or add something unique to the "PageWithSort" route, e.g.
Adding
/IDas hard coded part of the URL will make it distinguishable from the other routes (assuming there is not SortColumn calling "ID").