Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a route for /News/5 to my news controller

I am trying to identify how to map a route for /News/5 to my news controller.

This is my NewsController:

public class NewsController : BaseController
{
    //
    // GET: /News

    public ActionResult Index(int id)
    {
        return View();
    }

}

This is my Global.asax.cs rule:

        routes.MapRoute(
            "News", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "News", action = "Index", id = -1 } // Parameter defaults
        );

I try to go to /News/5 but I receive a resource not found error, however when going to /News/Index/5 it works?

I have tried just {controller}/{id} but that just produced the same issue.

Thanks!

like image 438
ElveMagicMike Avatar asked Feb 17 '12 16:02

ElveMagicMike


People also ask

Is there an app for mapping a route?

The most popular route planner in the world is Google Maps. It's reliable, easy to use — and free.

Can you choose your route on Apple Maps?

With a route showing in the Maps app , you can select various options before you tap Go. Choose an alternate route: If alternate routes appear, you can tap one on the map to take it (or tap Go next to its description in the route card).


1 Answers

Your {controller}/{id} route was correct but you problaby registered it AFTER the other route. In the route list it searches top down and the first match it finds wins.

To help steer routing I would suggest creating route constraints for this to ensure that #1 the controller exists and #2 the {id} is a number.

See this article

Mainly:

 routes.MapRoute( 
        "Index Action", // Route name 
        "{controller}/{id}", // URL with parameters EDIT: forgot starting "
        new { controller = "News", action = "Index" },
        new {id= @"\d+" }
    ); 
like image 152
Nick Bork Avatar answered Sep 21 '22 07:09

Nick Bork