An Optional Parameter means:
The parameter is not mandatory in the URL.
If the user does not provide it, the application will still work.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);Here, id is optional.
URL:
/Student/Details/5
Here:
URL:
/Student/Details
Even without ID, the action will still execute.
public ActionResult Details(int? id)
{
if (id == null)
{
return Content("No ID Provided");
}
return Content("Student ID: " + id);
}
Notice:
We used int? (nullable int).
Imagine a library system.
If no ID is provided, show all books.
If ID is provided, show specific book.
That is Optional Parameter concept.
[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.
User enters:
Routing automatically maps URL to Action method.
✔ Optional parameter makes URL flexible
✔ ID can be missing
✔ Use int? for nullable parameter
✔ Improves user-friendly routing
We want to create a simple Student page.
Open RouteConfig.cs and make sure this line exists:
routes.MapMvcAttributeRoutes();
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(); } } }
Right-click on Index action → Add View
@{ ViewBag.Title = "Student Page"; } <h2>@ViewBag.Message</h2>
http://localhost:1234/students
http://localhost:1234/students/Ali
If you visit:
In this route:
[Route("students/{studentName?}")]
Think like a library:
That is optional routing concept.
Use {parameter?} to make parameter optional
Use string or int? in action method
If no value → parameter becomes null
Simple and flexible URL system