ProgrammerGuide.Net | Step by Step Programmer Guide

How to Specifying that a Parameter is Optional in MVC Attribute Routing? | ASP.Net MVC Interview Question

  • You can do it by Specifying that a parameter is Optional (via the ‘?’ modifier).
  • This should be done after inline constraints.
  • Well,it’s like this  [Route(“Pet/{message:maxlength(4)?}”)]
              
        PetController.cs


        // eg: /Pet/good
        [Route(“Pet/{message:maxlength(4)?}”)]
        public ActionResult PetMessage(string message)
        {
            return View();
        }


Key points of the above code

  • In the above example, /Pet/good and /Pet will Route to the PetMessage Action.
  • The route /Pet also works hence of the Optional modifier.
  • But /Pet/good-bye will not route above Action , because of the maxlength(4) constraint.

Above Routes on Browser are as below

parameter is Optional

Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?