简体   繁体   English

如何对不同的MVC控制器进行ajax调用

[英]How to make ajax calls to different MVC controllers

I'm getting error 404 while making ajax calls to my MVC controller对我的 MVC 控制器进行 ajax 调用时出现错误 404

Here is the scenario:这是场景:

I have 2 controllers:(PartnerControler,GettingSartedController)我有 2 个控制器:(PartnerControler,GettingSartedController)

While on the getting started page: http://mysite/GettingStarted/ I make the following ajax call:在入门页面上: http://mysite/GettingStarted/我进行了以下 ajax 调用:

$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.我在调用控制器时收到 404。

when I add the exact register method to the gettingstarted controller and change the ajax URL to the following it works:当我将确切的 register 方法添加到 Gettingstarted 控制器并将 ajax URL 更改为以下内容时,它会起作用:

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?如何通过修改上述脚本来实现这一点?

If you have separate js files, you can use workaround like below 如果您有单独的js文件,则可以使用以下解决方法

<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 并将此element's attribute用作要在您的http调用中使用的url

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

I found another very good answer here in https://stackoverflow.com/a/57274117/14181068 for Ajax call to a different controller我在https://stackoverflow.com/a/57274117/14181068 中找到了另一个非常好的答案,用于对不同控制器的 Ajax 调用

This is the summary i got from the answer.这是我从答案中得到的总结。

url on ajax 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);
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM