Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC4 routing issue

I've searched Stack for ages, read the MSDN docs and used Bing but cannot see why this won't work! I've got the relevant code below + the routes. The route called Browse works just fine, but the productCode param for the Details route is always equal to nothing. If I make any mods I keep getting the 'resource not found' 404 page.

' Lives in controller called 'Details'
' Usage: site.com/details/abc123
Function Index(productCode As String) As ActionResult

' Lives in controller called 'Browse'    
' Usage: site.com/browse/scifi/2
Function Index(genre As String, Optional page As Integer = 1) As ActionResult

The routes are:

routes.MapRoute( _
        "Browse", _
        "{controller}/{genre}/{page}", _
        New With {.controller = "Browse", .action = "Index", .id = UrlParameter.Optional, .page = UrlParameter.Optional}
    )

    routes.MapRoute( _
        "Details", _
        "details/{productCode}", _
        New With {.controller = "Details", .action = "Info", .productCode = UrlParameter.Optional}
    )
like image 308
Alex Guerin Avatar asked May 25 '12 08:05

Alex Guerin


People also ask

What is ASP Net mvc4?

ASP.NET MVC 4 is a framework for developing highly testable and maintainable Web applications that follow the Model-View-Controller (MVC) pattern. The framework encourages you to maintain a clear separation of concerns— views for UI, controllers for handling user input, and models for domain logic.

Can we have multiple routing in MVC?

Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.

How do I enable routing in .NET core?

Inside the ConfigureRoute method, you can configure your routes; you can see that this method has to take a parameter of type IRouteBuilder. The goal of routing is to describe the rules that ASP.NET Core MVC will use to process an HTTP request and find a controller that can respond to that request.


1 Answers

The order does matter when defining your routes.

When you request site.com/details/abc123 I think it matches your first route.

You will get

controller = "details"

action = "Index"

genre = "abc123"

Which is why your productCode is null.

Switch the two route.MapRoute statements around, it should fix your problem.

Your second route does have action set to info rather than index, but i'm assuming that is a typo?

like image 146
Chris Diver Avatar answered Sep 27 '22 23:09

Chris Diver