user1526912
user1526912

Reputation: 17230

How to make ajax calls to different MVC controllers

I'm getting error 404 while making ajax calls to my MVC controller

Here is the scenario:

I have 2 controllers:(PartnerControler,GettingSartedController)

While on the getting started page:http://mysite/GettingStarted/ I make the following ajax call:

$scope.SubmitRegistration = function() {
  return $http({
    url: '/partner/register',
    method: 'POST',
    data: $scope.UserAccount,
    headers: {
      'Content-Type': 'application/json'

I get a 404 on the call to the controller.

when I add the exact register method to the gettingstarted controller and change the ajax URL to the following it works:

url: '/gettingstarted/register',

When on web a page that uses a specific controller can you make calls to another controller?

How can this be achieved modifying the above script?

Upvotes: 0

Views: 2201

Answers (2)

user14181068
user14181068

Reputation: 359

I found another very good answer here in https://stackoverflow.com/a/57274117/14181068 for Ajax call to a different controller

This is the summary i got from the answer.

url on ajax result
your/path http://example.com/Home/your/path
~/your/path http://example.com/Home/~/your/path or http://example.com/your/path
.../your/path http://example.com/Home/.../your/path
../your/path go up one directory level, resulting in http://example.com/your/path.
/your/path http://example.com/your/path

sample

        $.ajax({
            type: 'Get',
            url: "YourUrlHere",
            data: { id: $('#inputId').val() },
        })
        .done(function (response) {
            if (response.length > 0) {                
            }
        })
        .fail(function (error) {
            alert(error.StatusText);
        });

Upvotes: 0

Nitin Varpe
Nitin Varpe

Reputation: 10694

If you have separate js files, you can use workaround like below

<input type="hidden" id="registerurl" data-register-url="@Url.Action("register", "partner")"/>

and use this element's attribute as url to be used in your http call

var urlRegisterPartner = $('#registerurl').data('register-url');

Upvotes: 2

Related Questions