How to make ajax calls to different MVC controller

2019-09-05 08:55发布

问题:

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?

回答1:

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');