C # route redirecting to wrong action

3

I have an action that returns a PartialView

[HttpPost]
public ActionResult SelectCidadesPorCodigoUF(int idUF)
{
   //It do something and returns a PartialView
}

This action is mapped as follows:

routes.MapRoute(
     name: "SelecionarCidades",
     url: "SelecionarCidades/{idUF}", 
     defaults: new { controller = "Regioes", action = "SelectCidadesPorCodigoUF" }
);

Finally I have made an AJAX request to this action:

$.ajax({
   type: 'POST',
   url: '/Regioes/SelectCidadesPorCodigoUF',
   data: { 'idUF': idUF },
   dataType: 'html',
   cache: false,

   beforeSend: function (data) {
   },

   success: function (data) {
        //do something
   },

   error: function (data) {
       //do something
   }
});

The problem I have is that this ajax request does not find this action SelectCidadesPorCodigoUF , but the action Index , that is, it goes to the wrong action. Someone who has gone through this could help me:

    
asked by anonymous 08.11.2017 / 17:50

2 answers

2

use:

 routes.MapRoute(
                name: "Teste",
                url: "SelecionarCidades/{idUF}",
                defaults: new { controller = "Regioes", action = "SelectCidadesPorCodigoUF", idUF = UrlParameter.Optional }
            );

Check the order in which the rule was placed. It has to come before the default route, otherwise it will not work.

    
08.11.2017 / 18:01
1

I think the problem is in the url of your route. You have put "Select Cities" and not "SelectCodeCategoryUF" which is the correct Action name and the name you call in Ajax.

routes.MapRoute(
 name: "SelecionarCidades",
 url: "SelecionarCidades/{idUF}", 
 defaults: new { controller = "Regioes", action ="SelectCidadesPorCodigoUF",idUF = UrlParameter.Optional  }
);

The correct route would be:

routes.MapRoute(
 name: "SelecionarCidades",
 url: "SelectCidadesPorCodigoUF/{idUF}", 
 defaults: new { controller = "Regioes", action ="SelectCidadesPorCodigoUF",idUF = UrlParameter.Optional  }
);
    
08.11.2017 / 18:12