4

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

2 Answers 2

16

your can write your actionmethod like

public ActionResult index(int? id)
{
   if(id.HasValue)
   {
       //do something  
   }
   else
   {
      //do something else
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just a quick note, you can use the optional parameters of C# 4 as well. This means you'll have public ActionResult index(int id = 0).
8

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.

3 Comments

I ... can't find a mention of that attribute. What's the deal? Can you point me to the "using" that would include it?
@jcolebrand: check my linked blog post and read all the details. It should explain the reasoning behind this attribute.
Yeah, I didn't read all the details on the first pass. Missed that you had self-defined the attribute class. Using it already ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.