TTCG
TTCG

Reputation: 9113

Custom Routing not working in MVC5

First of all, I am very new to MVC and this is my first ever project.

I am trying to achieve the custom routing URL like the following:

http://mywebsite/MDT/Index/ADC00301SB

Similar to... http://mywebsite/{Controller}/{Action}/{query}

In my RouteConfig.cs, I put the following

routes.MapRoute(
                name: "SearchComputer",
                url: "{controller}/{action}/{query}",
                defaults: new { controller = "MDT", action = "Index", query = UrlParameter.Optional }
            );

In My MDTController.cs, I have the following code

public ActionResult Index(string query)
        {
            Utils.Debug(query);
            if (string.IsNullOrEmpty(query) == false)
            {
                //Load data and return view 
                //Remove Codes for clarification
            }

            return View();
        }

But it's not working and I always get NULL value in query if I used http://mywebsite/MDT/Index/ADC00301SB

But if I used http://mywebsite/MDT?query=ADC00301SB, it's working fine and it hits the Controller Index method.

Could you please let me know how I could map the routing correctly?

Upvotes: 0

Views: 1560

Answers (3)

Lewis Hai
Lewis Hai

Reputation: 1214

You can change it to

routes.MapRoute(
            name: "SearchComputer",
            url: "MDT/{action}/{query}",
            defaults: new { controller = "MDT", action = "Index", query = UrlParameter.Optional }
        );

Upvotes: 0

Ric
Ric

Reputation: 13248

One issue that I have encountered is that placing your route below the default route will cause the default to be hit, not your custom route.

So place it above the default route and it will work.

A detailed explanation from MSDN:

The order in which Route objects appear in the Routes collection is significant. Route matching is tried from the first route to the last route in the collection. When a match occurs, no more routes are evaluated. In general, add routes to the Routes property in order from the most specific route definitions to least specific ones.

Adding Routes to an MVC Application.

Upvotes: 1

Bartosz Czerwonka
Bartosz Czerwonka

Reputation: 1651

You should add your MapRoute before default MapRoute, because order in RouteCollection is important

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "SearchComputer",
               url: "{controller}/{action}/{query}",
               defaults: new { controller = "MDT", action = "Index", query = UrlParameter.Optional }
           );

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


        }

Upvotes: 1

Related Questions