Since we will continue working with the same example from the previous article. A URI parameter can be made optional by appending a question mark ("?") to the route parameter. Additionally, you can set a default value using parameter = value. If this concept is unclear right now, don’t worry—we will explore both approaches with examples.
To better understand this concept, let's create a new controller named HomeController inside the Controllers folder and insert the following code. In the MVC action method, the studentName parameter is marked as optional by adding a question mark [Route("MVCTest/{studentName?}")]. This means if no value is provided in the URL, the parameter will be assigned a null value. However, if a value is specified, it will be mapped to the studentName parameter. In the Web API action method, a default value is assigned to the studentName parameter directly within the Route attribute: [Route("WEBAPITest/{studentName=Noorain}")]. This ensures that if no value is provided, it automatically defaults to "Noorain".
namespace AttributeRoutingDemoInMVC.Controllers
{
public class HomeController : Controller
{
// Optional URI Parameter
// URL: /MVCTest/
// URL: /MVCTest/Pranaya
[Route("MVCTest/{studentName ?}")]
public ActionResult MVC(string studentName)
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
// Optional URI Parameter with default value
// URL: /WEBAPITest/
// URL: /WEBAPITest/Noorain
[Route("WEBAPITest/{studentName = Noorain}")]
public ActionResult WEBAPI(string studentName)
{
ViewBag.Message = "Welcome to ASP.NET WEB API!";
return View();
}
}
}
In the given example, both /MVCTest and /MVCTest/Noorain will navigate to the "MVC" action method. Similarly, /WEBAPITest and /WEBAPITest/Noorain will be directed to the "WEBAPI" action method. Now, add the following two views:
@{
ViewBag.Title = "MVC";
}
@ViewBag.Message
@{
ViewBag.Title = "WEBAPI";
}
@ViewBag.Message
Now, launch the application and visit the following four URLs to verify that everything functions as expected.