c# - How to handle similar routes when one has integer parameter and other has string? -


i building set of mvc pages pertaining managing users, , have following routes defined in routeconfig.cs:

routes.maproute(name: "users", url: "users", defaults: new { controller = "users", action = "index" }); routes.maproute(name: "user details", url: "users/{id}", defaults: new { controller = "users", action = "edit",  id = urlparameter.optional }); routes.maproute(name: "user creation", url: "users/create", defaults: new { controller = "users", action = "create" }); 

the problem i'm facing when navigate /users/create, following error gets thrown:

the parameters dictionary contains null entry parameter 'id' of non-nullable type 'system.int64' method 'system.web.mvc.actionresult edit(int64)' in 'myui.controllers.userscontroller'. optional parameter must reference type, nullable type, or declared optional parameter. parameter name: parameters

it appears unable distinguish between numerical id being passed {id} , create being passed route right location. makes bit of sense, since there's hint routing {id} number, how know?

my question breaks down "how mvc routing distinguish between these 2 cases, numeric id passed in, in contrast string being passed in call different function in controller?"

you need add custom constraint route:

routes.maproute("users route",     "users/{id}",     new { controller = "users", action= "getusers" },     new { userid = @"\d+" } ); 

this tells routing engine in order users route hit, there needs numerical route segment {userid} route segment is.

a custom constraint can implements irouteconstraint; in case, i'm using regex determine route constraint should be.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -