1
votes

I am not an advanced developer. I just started working with MVC. Few days back I had seen an example of ASP.NET MVC routing code where two controller or action name has been referenced.

routes.MapRoute(
    name: "test",
    url: "{controller}/{action}/{page}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    defaults: new { action = "Index" }
);

Just started working with ASP.NET MVC, so I am curious to know what is the objective to mention controller or action name twice in routing code?

In above example there are two defaults.... When and why is it required?

Just requesting some one to explain the same with a nice example.

Thanks in advance.

1
as you mentioned, where are two controller names in your configuration ?? - Ray
can you share the source from where you got this code? I have never seen "defaults" or any other parameter for that matter gets repeated in MapRoute method. There is no point in doing that honestly. Mvc template by default has only one "defaults" parameters, and it should give you compile error if you specify it twice! - Nirman
i will but i need to browse my browser history. so will update my post with new link later. thanks - Monojit Sarkar
@Nirman see this url stackoverflow.com/a/19595133/6188148 here you will see two default in routing. - Monojit Sarkar
@MonojitSarkar, I just could see your link. Check the answer of NightOwl1888 which should clarify the things. Also, mark it as answered so other visitors of this question gets benefited. - Nirman

1 Answers

0
votes

The example from the link you posted:

context.MapRoute(
    "UserHome",
    "User/{id}",
    new { action = "Index", controller = "Home", area = "User", id = 0, 
        httproute = true },
    new { controller = @"Home", id = @"\d+" }
);

is a bit confusing, because it is using anonymous types without named arguments. If you add named arguments to that example, it would look like this:

context.MapRoute(
    name: "UserHome",
    url: "User/{id}",
    defaults: new { action = "Index", controller = "Home", area = "User", id = 0, 
        httproute = true },
    constraints: new { controller = @"Home", id = @"\d+" }
);

This makes it more clear what is going on here. The example is not showing two sets of defaults, instead there are constraints that limit the range of values that will match.

It basically says:

  1. controller = @"Home" - When generating the URL, only match this route if controller route value is Home.
  2. id = @"\d+" - Match if the id route value contains only numerals.

Actually, both of the above constraints run for both incoming URL matching and URL generation, but controller = @"Home" will always be true when matching the incoming URL because the default value is the only thing that can set it (and the default value is also Home).