Routing with Optional Parameter in ASP.NET MVC


What is an Optional Parameter?

An Optional Parameter means:

The parameter is not mandatory in the URL.
If the user does not provide it, the application will still work.


Why Do We Use Optional Parameters?

  • To make URL flexible
  • To avoid errors when parameter is missing
  • To provide default behavior
  • To make user-friendly URLs

Basic Default Route with Optional Parameter

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new 
    { 
        controller = "Home", 
        action = "Index", 
        id = UrlParameter.Optional 
    }
);

Here, id is optional.


Example 1: Without Optional Parameter

URL:

/Student/Details/5

Here:

  • Student → Controller
  • Details → Action
  • 5 → ID

Example 2: With Optional Parameter (ID Missing)

URL:

/Student/Details

Even without ID, the action will still execute.


Controller Example

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return Content("No ID Provided");
    }

    return Content("Student ID: " + id);
}

Notice:
We used int? (nullable int).


Real-Life Example (Very Simple)

Imagine a library system.

  • /books → Show all books
  • /books/5 → Show book with ID 5

If no ID is provided, show all books.
If ID is provided, show specific book.

That is Optional Parameter concept.


Attribute Routing with Optional Parameter (Advanced)

[Route("student/details/{id?}")]
public ActionResult Details(int? id)
{
    if (id == null)
        return Content("Showing All Students");

    return Content(
        "Student ID: " + id
    );
}

Here, {id?} makes the parameter optional.


Important Rules

  • Optional parameters must come at the end of the URL
  • Use nullable type (int?) in Action method
  • Use UrlParameter.Optional in default route
  • Use ? symbol in Attribute Routing

Routing Flow Example

User enters:

  • /Student/Details → id = null
  • /Student/Details/10 → id = 10

Routing automatically maps URL to Action method.


Summary

✔ Optional parameter makes URL flexible
✔ ID can be missing
✔ Use int? for nullable parameter
✔ Improves user-friendly routing


Complete Example: Routing with Optional Parameter


Scenario

We want to create a simple Student page.

  • If no name is provided → Show "All Students"
  • If name is provided → Show "Student Name"

Step 1: Enable Attribute Routing

Open RouteConfig.cs and make sure this line exists:

routes.MapMvcAttributeRoutes();

Step 2: Create StudentController

using System.Web.Mvc;

namespace RoutingDemo.Controllers
{
    public class StudentController : Controller
    {
        // Optional Parameter Example
        // URL: /students
        // URL: /students/Ali

        [Route("students/{studentName?}")]
        public ActionResult Index(string studentName)
        {
            if (string.IsNullOrEmpty(studentName))
            {
                ViewBag.Message = "Showing All Students";
            }
            else
            {
                ViewBag.Message = "Student Name: " + studentName;
            }

            return View();
        }
    }
}

Step 3: Create View (Index.cshtml)

Right-click on Index action → Add View

@{
    ViewBag.Title = "Student Page";
}

<h2>@ViewBag.Message</h2>

Test the URLs

http://localhost:1234/students

http://localhost:1234/students/Ali

What Happens?

If you visit:

  • /students → studentName = null → Shows "All Students"
  • /students/Ali → studentName = "Ali" → Shows "Student Name: Ali"

How It Works

In this route:

[Route("students/{studentName?}")]
  • ? makes the parameter optional
  • If no value → parameter becomes null
  • If value exists → it is passed to action method

Real-Life Example

Think like a library:

  • /books → Show all books
  • /books/History → Show History books only

That is optional routing concept.


Summary

Use {parameter?} to make parameter optional
Use string or int? in action method
If no value → parameter becomes null
Simple and flexible URL system