JCIsola
JCIsola

Reputation: 108

Calling 2 Actions from 2 different Views in the same Controller. Always the same action is called (the first in the Route config)

I have a Controller with the name Pedidos inside there are 2 methods:

    public ActionResult Create(string id)
    {
        //...
    }

    public ActionResult CreateEAN(string id)
    {
        //...
    }

When I call each method from javascript (from inside each corresponding View), always the same method is called, the one that's first in the Route config, in this case it's CreateEAN this is the Route config:

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

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}",
        defaults: new { controller = "Sesion", action = "Identificacion" }
    );

    routes.MapRoute(
    "Pedidos1",
    "{Pedidos}/{CreateEAN}/{id}",
    new
    {
        controller = "Pedidos",
        action = "CreateEAN",
        id = UrlParameter.Optional
    });

    routes.MapRoute(
    "Pedidos2",
    "{Pedidos}/{Create}/{id}",
    new
    {
        controller = "Pedidos",
        action = "Create",
        id = UrlParameter.Optional
    });
}

Here is how I call this method from Javascript:

1)

<script type="text/javascript">
    function CambioDeposito()
    {
        var sid = $("#ddlDeposito").val();
        window.location.href = '@Url.Action("CreateEAN", "Pedidos")' + '/' + sid;
    }
</script>

2)

<script type="text/javascript">
        function CambioDeposito()
        {
            var sid = $("#ddlDeposito").val();
            window.location.href = '@Url.Action("Create", "Pedidos")' + '/' + sid;
        }
</script>

If I change the order in Route Config then Create is the one that's always called. I understand they are similar but those 2 actions have different names! why the routing is failing like this? How can I fix this so the correct method is called in each case?

Thanks!!

Upvotes: 0

Views: 33

Answers (1)

Okan Kocyigit
Okan Kocyigit

Reputation: 13441

Your routing URLs are wrong because of curly brackets.

Using curly brackets in URL string makes that keyword parameter. Your only parameter is {id}, so you should remove other curly brackets.

routes.MapRoute(
    "Pedidos1",
    "Pedidos/CreateEAN/{id}",
    new
    {
        controller = "Pedidos",
        action = "CreateEAN",
        id = UrlParameter.Optional
    });

routes.MapRoute(
    "Pedidos2",
    "Pedidos/Create/{id}",
    new
    {
        controller = "Pedidos",
        action = "Create",
        id = UrlParameter.Optional
    });

Upvotes: 1

Related Questions