2

In MVC 4 application while defining routing I can provide a list of default parameters. What value shall I provide for optional parameter: UrlParameter.Optional or empty string?

Examples:

routes.MapRoute("simple", "{controller}/{action}/{id}",
  new {controller = "Home", action = "Index", id = UrlParameter.Optional});
routes.MapRoute("simple", "{controller}/{action}/{id}",
  new {controller = "Home", action = "Index", id = ""});

Is there any difference between id = "" and id = UrlParameter.Optional in above examples?

Please note that some controller actions will be using id (of type string) and some will be parameterless.

1 Answer 1

4

The difference is subtle and but almost unimportant

UrlParameter.Optional means a null will be passed to the Action Method in lieu of a value.

id = "" means a default value of "" (not null) will be passed to the Action Method.

In both cases, not including an id parameter in your route will NOT stop the MVC framework from finding the right method.

In the case of UrlParameter.Optional, you should make all relatable Action Methods take a nullable parameter

Type matters

You should NOT apply id="" to routes that use ints.

Sign up to request clarification or add additional context in comments.

1 Comment

Also of importance is only the last parameter in the list can have a default value of UrlParameter.Optional

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.