HOW ROUTING WORKS IN ASP.NET MVC4

Pravesh Singh

Total Post:101

Points:709
Posted by  Pravesh Singh
 1064  View(s)
Ratings:
Rate this:

I'm developing an ASP.NET MVC4 application and I'm new. I have two MapRoutes for routing.

 

routes.MapRoute("Char",

                "ABC/Alpha/{number1}",

                 defaults: new { Controller = "ABC", action = "Alpha" });          

 

routes.MapRoute(

            name: "Default",

            url: "{controller}/{action}/{id}",

            defaults: new { controller = "Home", action = "Index",  id=UrlParameter.Optional }

        );

I didn't assign any default value to the number1 in the MapRoutes. But I know it is mandatory because it is in the URL path.

 

If I didn't provide any parameter in the url (when I run the app), I should get an error but I didn't.


Can anyone help me?

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: How routing works in ASP.NET MVC4

    Hi Pravesh, 


    The Route path is checked from top to bottom, so in the first case

     

    {Controller}/{Action}/{ID}

    is passed by you (mention the id is must here) so the First routepath works

     

    but Magic you was expecting the second case to throw an error, and it should have because if your Action is like

     

    public ActionResult ActionName(int id)

    {

    //some Code

    }

    then for sure it would have thrown error like Action

     

    "Cannot convert null to 'int' because it is a non-nullable value type"

    and i'm Pretty sure your Action will be having either

     

     public ActionResult(int? id)

     {//Some Code here}

    or

     

    Public ActionResult()

    {

    //Some Code here

     }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!