Illy Coslova
Illy Coslova

Reputation: 41

MVC routing with optional parameter

I have this route set up:

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 it being present or not present.

Thanks

Upvotes: 4

Views: 6020

Answers (2)

Robert Koritnik
Robert Koritnik

Reputation: 105071

How to avoid nullable action parameters (and if statements)

As you've seen by @Muhammad's answer (which is BTW the one to be accepted as the correct answer) it's easy to get optional parameters (any route parameters actually) into controller actions. All you you have to make sure is that they're nullable (because they're optional).

But since they're optional you end up with branched code which is harder to unit test an maintain. Hence by using a simple action method selector it's possible to write something similar to this:

public ActionResult Index()
{
    // do something when there's not ID
}

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

A custom action method selector has been used in this case and you can find its code and detailed explanation in my blog post. These kind of actions are easy to grasp/understand, unit test (no unnecessary branches) and maintain.

Upvotes: 8

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17794

your can write your actionmethod like

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

Upvotes: 16

Related Questions