Reputation: 111
Controller Action method:
public ActionResult Details(int key)
{
CustomerContext customerContext = new CustomerContext();
var customer = customerContext.Customers.Single(c => c.CustomerKey == key);
return View(customer);
}
Registered Routes:
routes.MapRoute(
name: "Details",
url: "{controller}/{action}/{key}",
defaults: new { controller = "Customer", action = "Details", key = UrlParameter.Optional } );
When I use this uri :
http://localhost/Lab100_1/customer/details?key=11000
I get the proper customer details... however
When I use this uri :
http://localhost/Lab100_1/customer/details/11000
I get this error:
The parameters dictionary contains a null entry for parameter 'key' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'Lab100_1.Controllers.CustomerController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
What I already tried : in then route config: defaults (passed a default value):
new { controller = "Customer", action = "Details", key = 0}
in the controller action method made the parameter nullable:
public ActionResult Details(int? key)
however I get the same error - I have a feeling if passing the parameter as query string works... then why passing it as URI parameter is not working...??? I have the route config in place... any help is much appreciated... thanks
Upvotes: 1
Views: 2218
Reputation: 17182
I think your config is below the Default Route config. You should get it as first priority than the default route. So your route config should be like this -
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default1",
url: "{controller}/{action}/{key}",
defaults: new { controller = "Customer", action = "Details", key = UrlParameter.Optional },
constraints: new { key = @"\d+" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Then it should work. UPDATED: Use Constraint.
Upvotes: 1