Attribute Routing with Optional Parameter

Attribute Routing with Optional Parameter

In this article, I will discuss the Attribute Routing with Optional Parameter with one example

Please read our last article of Attribute Routing before proceeding to this article as we are going to work with the same example that we started in our last article. In our last article, we discuss the following things.

  1. Why we need attribute routing?
  2. What is Attribute Routing?
  3. How to Implement Attribute Routing?
  4. What are the advantages of using Attribute Routing?

Using the [Route] attribute to define routes is called Attribute Routing.

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.

URL1: http://localhost:58316/MVCTest

URL2: http://localhost:58316/MVCTest/Pranaya

URL3: http://localhost:58316//WEBAPITest

URL4: http://localhost:58316//WEBAPITest/Pranaya

In the next article, I will discuss Route Prefix in Attribute Routing.

If you want to learn more about Attribute Routing then please visit the MSDN Site.

SUMMARY
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 need. 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 *