Route c# redirecting to wrong action

Asked

Viewed 67 times

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, and yes the action Index, I mean, it goes to the wrong action. Someone who’s been through this could help me:

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.

1

I believe the problem lies at the url of your route. You have entered "Selectactions" and not "Selectcitingsporcode" which is the correct name of Action 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  }
);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.