Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC routes.MapRoute name property

I'm brand new to MVC so please bear with me as I'm only on the second page of the MS Tutorial (see last code example). For the HelloWorldController the following MapRoute is added:

routes.MapRoute(
                name: "Hello",
                url: "{controller}/{action}/{name}/{id}");

I'm just wondering, is it purely the pattern matching that does the work and the name "Hello" is just for my own reference? If so, are there not naming conventions that should be followed saying the MapRoute should be called HelloWorldWelcome, where welcome is a method inside the HelloWorldController.cs (see above link). Or am i being pedantic?

like image 330
rory Avatar asked Sep 05 '14 19:09

rory


1 Answers

The route name is also used by the UrlHelper class. For example:

var url = Url.Route("Hello", new
{
    controller = "SomeController",
    action = "SomeAction",
    name = "charlie",
    id = 123
});

This will generate a matching URL.

This feature is much more useful when you use Attribute Routing. For example, if on some controller you have an action:

[RoutePrefix("api/phonebook")]
public class PhonebookController
{
    [HttpGet("contact/{id}", Name = "GetContact")]
    public Contact GetContact(int id)
    {
        ...
    }
}

In other code you could use Url.Route("GetContact", new { id = 7 }) to generate the URL /api/phonebook/contact/7.

like image 104
Timothy Shields Avatar answered Nov 10 '22 18:11

Timothy Shields