How to access Action in another Controller via Ajax?

Asked

Viewed 535 times

4

I have an Aspnet MVC project structured as follows:

Projeto
    L
      Areas
         L
           Area1
               L
                Controllers
                       L
                        MeuControllerArea1Controller.cs
                Views
           Area2
               L
                Controllers
                       L
                        MeuControllerArea2Controller.cs
                Views
                     L
                       MinhaView.cshtml

In Meucontrollerarea1, I have a public method (Minhaactionarea1) that returns a json, I want to access it from Minhaview who is in Area2.
The code below has not worked, because when running, it searches Minhaactionarea1 in Meucontrollerarea2.

function ObterResultado() {
        $.post('@Url.Action("MinhaActionArea1", "../Area1/MeuControllerArea1")')
            .done(function (data) {
                // Código de sucesso...
            })
            .fail(function () {
                // Código de falha...
            });
    }

Note: I am using Arearearegistration.

  • $.post('.. /Area1/Meucontrollerarea1/Minhaactionarea1')

  • It worked perfectly, post as reply @Joaopaulo the fault was mine here.

2 answers

4

Just put as string, do not need to use C code#:

$.post('../Area1/MeuControllerArea1/MinhaActionArea1')

1


After the @Joaopaulo tip in the comments I managed perfectly using:

$.post('../Area1/MeuControllerArea1/MinhaActionArea1')

Another option (which I have chosen) can be made with Urlhelper.Action Method, because as I observed at the end of the question, I am using Arearearegistration.
I searched and found a another way to use the @Url.Action passing just to area which is the controller and action:

@Url.Action("ActionName", "ControllerName", new { area = "AreaName" })

The code went like this:

function ObterResultado() {
        $.post('@Url.Action("MinhaActionArea1", "MeuControllerArea1", new { area = "Area1" })')
            .done(function (data) {
                // Código de sucesso...
            })
            .fail(function () {
                // Código de falha...
            });
    }

Browser other questions tagged

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