简体   繁体   中英

Custom map route is not working in asp.net mvc

I have an custom mvc route it's not working. if i define the route before home route then it's working otherwise not.

this code is not working.

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

       routes.MapRoute(
          "Citysearch",
         "{state}",
         new { controller = "Dashboard", action = "GetDynamicContent" }
       );

when i define the citysearch first then it's working something like this

routes.MapRoute(
              "Citysearch",
             "{state}",
             new { controller = "Dashboard", action = "GetDynamicContent" }
           );

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

and another problem is this is the url of city search http://localhost:51381/dynamic-content . dynamic-content this is my state paramter. It's calling of my Dashboard/GetDynamicContent . but problem is when application run after login url is http://localhost:51381/Home it is calling always Dashboard/GetDynamicContent how to get rid of this problem please help me.

Routes are read from top to bottom. Therefore, the first route match will be used when routing.

Try this

routes.MapRoute(
    "Home",
    "Home/{action}",
    new { controller = "Home", action = "index" }
);

routes.MapRoute(
    "Citysearch",
    "DynamicContent/{state}",
    new { controller = "Dashboard", action = "GetDynamicContent" }
);

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

You have to use some fix part in your url as shown below DynamicContent/ to solve issue you are facing. And your url should be like http://localhost:51381/DynamicContent/dynamic-content .

routes.MapRoute(
    "Citysearch",
    "DynamicContent/{state}",
    new { controller = "Dashboard", action = "GetDynamicContent" }
);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM