How to access Action on another Controller via Ajax?

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 MyControllerArea1 , I have a public method ( MinhaActionArea1 ) that returns a json , I want to access it from MyView that is in Area2 . Home The code below has not worked, because when it runs, it looks for MyActionArea1 in MyControllerArea2 .

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

Note: I'm using AreaRegistration .

    
asked by anonymous 28.08.2015 / 15:56

2 answers

1

After the tip of @JoaoPaulo in the comments I managed perfectly using:

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

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

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

The code looks 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...
            });
    }
    
28.08.2015 / 16:39
4

Simply put as a string, you do not need to use C # code:

$.post('../Area1/MeuControllerArea1/MinhaActionArea1')
    
28.08.2015 / 17:05