2

I am trying to call a different Controller method in an Ajax call. I have looked at different posts for a solution but because I do not exactly understand what their solutions are (Links at bottom). I am calling my ajax call from my Home Controller, trying to call a method in my Production Controller.

"Request URL: http://localhost.59223/Home/Production/CreateNewProductionGoal"

This is the error I am getting.

I have tried changing the URL to .../Production/CreateNewProductionGoal and to ~/Production/CreateNewProductionGoal, as suggested online. Neither of these implementations worked because I was getting a 404 error, page not found.

One of the linked solutions mentions using a loc var key, of which I am unfamiliar.

The other suggests using a button which is not an option in my case.

            $.ajax({
            type: 'post',
            url: "Production/CreateNewProductionGoal",
            dataType: "json",
            data: data,  //Creating a ProductionGoalViewModel to pass into the CreateNewProductionGoal method
            success: function (data) {
                //$('#Dashboard').load("/Home/UpdateView/" + selectProductionLine);
            }
        });

Ajax call to different controller

How to make ajax calls to different MVC controllers

For clarification, I am looking for a step by step with explanation on how to Ajax call from one MVC controller to another.

Thanks!

Dvyn Resh
  • 980
  • 1
  • 6
  • 14
Kevin
  • 333
  • 1
  • 14

2 Answers2

6

You should include a leading / in your url to call the correct URL:

$.ajax({
    ...
    url: "/Production/CreateNewProductionGoal",
    ...
});

That way, the request will go to http://localhost.59223/Production/CreateNewProductionGoal instead.

The different paths, if you currently view http://example.com/Home/:

  • your/path: This will take the current path as start path, i.e. and add it to there, resulting in http://example.com/Home/your/path.

  • ~/your/path: can be used in asp.net server code, e.g. Razor to indicate the root of your website, only if it rendered. Browsers do not consider ~/ a special token, resulting in http://example.com/Home/~/your/path or http://example.com/your/path, when rendered

  • .../your/path: nothing special, resulting in http://example.com/Home/.../your/path

  • ../your/path: go up one directory level, resulting in http://example.com/your/path. But this will result in different paths for nested directories.

  • /your/path: absolute path, will always result in http://example.com/your/path, independently of nested directories.

For more on absolute and relative URL see Absolute vs relative URLs

Residuum
  • 11,878
  • 7
  • 40
  • 70
1

This might still be helpful for someone to use

$.ajax({
    ...
    url: "@string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/Production/CreateNewProductionGoal",
    ...
});
Bosco
  • 1,536
  • 2
  • 13
  • 25