MVC trace with optional parameter

I have this route installed:

routes.MapRoute( "home3", // Route name "home3/{id}", // URL with parameters new { controller = "home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); 

But in my controller, I don't know how to get the optional id parameter. Can someone explain how I can access this and how I deal with the fact that it is present or not.

thanks

+4
source share
2 answers

you can write your action method, for example

 public ActionResult index(int? id) { if(id.HasValue) { //do something } else { //do something else } } 
+16
source

Avoiding NULL parameter values โ€‹โ€‹(and if )

As you saw from @Muhammad's answer (which is BTW, the one that will be accepted as the correct answer), itโ€™s easy to get optional parameters (any route parameters actually) in the controllerโ€™s actions. All you need to do is make sure they are invalid (because they are optional).

But since they are optional, you get branched code that is harder to support unit test. Therefore, using a simple action action selector, you can write something similar to this:

 public ActionResult Index() { // do something when there not ID } [RequiresRouteValues("id")] public ActionResult Index(int id) // mind the NON-nullable parameter { // do something that needs ID } 

In this case, a special action selector was used, and you can find its code and a detailed explanation in my blog post . These actions are easy to understand / understand, unit test (without unnecessary branches) and maintain.

+8
source

Source: https://habr.com/ru/post/1345193/


All Articles