Attribute Routing with Optional Parameter

Attribute Routing with Optional Parameter in ASP.NET MVC

In this article, I am going to discuss the Attribute Routing with Optional Parameter with one example. Please read our previous article before proceeding to this article as we are going to work with the same example that we started in our previous article. In our previous article, we discuss the basics of Attribute Routing in ASP.NET MVC Application.

Attribute Routing with Optional Parameter:

You can also define a URI parameter as optional by adding a question mark (“?”) to the route parameter. You can also specify the default value by using parameter = value. We will see both these approaches with an example in this article.

To understand this, let’s add a controller within the controller folder with the name as HomeController and then copy and paste the below codes.

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/Pranaya
        [Route("WEBAPITest/{studentName = Pranaya}")]
        public ActionResult WEBAPI(string studentName)
        {
            ViewBag.Message = "Welcome to ASP.NET WEB API!";
            return View();
        }
    }
}

In the above example, both /MVCTest and /MVCTest/Pranaya will route to the “MVC” action method, similarly, /WEBAPITest and /WEBAPITest/Pranaya will route to the “WEBAPI” action method. Then add the below two views:

MVC.cshtml

@{
    ViewBag.Title = "MVC";
}
@ViewBag.Message

WEBAPI.cshtml

@{
    ViewBag.Title = "WEBAPI";
}
@ViewBag.Message

Now run the application and navigate to the below four URLs and see everything is working as expected.

  1. URL1: http://localhost:58316/MVCTest
  2. URL2: http://localhost:58316/MVCTest/Pranaya
  3. URL3: http://localhost:58316//WEBAPITest
  4. URL4: http://localhost:58316//WEBAPITest/Pranaya

In the next article, I am going to discuss Route Prefix in Attribute Routing with some examples. Here, in this article, I try to explain the Attribute Routing with Optional Parameter in ASP.NET MVC application. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *