简体   繁体   English

AJAX调用MVC5 ActionResult

[英]AJAX Call to MVC5 ActionResult

I am trying to figure out what is wrong with the following code: 我试图找出以下代码出了什么问题:

$(".ReportScore").click(function () {
    $.ajax({
        type: "GET",
        url: "/events/Tournaments/ReportScore",
        success: function() {
            location.reload();
        },
        error: function() {
            alert("The scores were not recorded");
        }
    });
});

When I type the url in the bar, it works without problems, however when I try to do an ajax call I get 404 Page not found error. 当我在栏中输入网址时,它可以正常工作,但是当我尝试进行ajax调用时,出现404 Page not found错误。

To clarify, when I click on the button I Get a popup saying "The scores were not recorded" and on developer tools I get a script error saying Page not found. 澄清一下,当我单击按钮时,我会弹出一个对话框,说“未记录分数”,在开发人员工具上,我遇到了一个脚本错误,提示未找到Page。

I also have a breakpoint in visusal studio on the method itself, but the point is never hit as the method is never called. 在方法本身上,我在visusal studio中也有一个断点,但是因为从未调用过该方法,所以一点都没有碰到。

Server Side Code: 服务器端代码:

public async Task<ActionResult> ReportScore()
{
    var a = "abc"
}

var a line is never hit. var一条线永远不会命中。

EDIT: 编辑:

I have another ajax call from the same script that works without problems: 我从同一脚本进行了另一个ajax调用,该调用没有问题:

$("#InvitedMember").autocomplete({
    source: function (request, response) {
        $.ajax({
            type: "POST",
            url: "/events/Teams/Members",
            data: { id: $("#InvitedMember").val() },
            success: function (data) {
                response($.map(data, function (item) {
                    return {
                        label: item.CustomUrl, value: item.CustomUrl
                    };
                }));
            }
        });
    },
    create: function () {
        $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
            return $('<li>')
                .append("<a><div>" + item.label + "</div></a>")
                .appendTo(ul);
        };
    },
    select: function (event, ui) {
        //you can access ui.item to get the selected item object.
        $("#InvitedMember").val(ui.item.value);
        return false;
    }
});

It is not a good idea to hardcode your url's like that. 像这样对URL进行硬编码不是一个好主意。 You should always use the Url.Action or Url.RouteUrl html helper methods to build the relative url to the action methods/endpoints you are accessing. 您应该始终使用Url.ActionUrl.RouteUrl html帮助器方法来为要访问的操作方法/端点构建相对URL。 These helper methods will take care of correctly building the url regardless of your current page/path. 无论您当前的页面/路径如何,这些帮助器方法都将正确构建URL。

Also, from your comment, it seems like events is the name of your virtual directory/application name in your IIS . 另外,从您的评论来看,事件似乎是IIS中虚拟目录/应用程序名称的名称 You should not use those in your code to build the urls as it might change based on your deployment. 您不应该在代码中使用这些URL来构建URL,因为URL可能会根据您的部署而改变。 What if you want aa copy of your code deployed to "http://staging.yourSite.com" ? 如果您想要将代码副本部署到"http://staging.yourSite.com"怎么办?

As long as you use the Url.Action helper method,it will build the correct relative url to your app and you do not need to worry about your IIS virutal directory/application name. 只要您使用Url.Action帮助程序方法,它就会为您的应用程序构建正确的相对URL,并且您无需担心IIS虚拟目录/应用程序名称。

var url = "@Url.Action("ReportScore","Tournaments")";

$.ajax({
    type: "GET",
    url:url,
    success: function (res) {
        alert('success happened');
        //location.reload();
    },
    error: function () {
        alert("The scores were not recorded");
    }
});

The above code will work if you have it in a razor view. 如果您在剃刀视图中使用上面的代码,它将起作用。 But if your ajax call code is in external js file, You may build the relative url to the app root and pass that to your js file and use that to build the url. 但是,如果您的ajax调用代码位于外部js文件中,则可以将相对URL构建到应用程序根目录,并将该URL传递给您的js文件,然后使用该URL来构建URL。 You can use the @Url.Content("~") to build the url to app root. 您可以使用@Url.Content("~")来构建应用程序根目录的URL。 If you want, you can build the url to specific action method itself. 如果需要,可以构建特定操作方法本身的URL。

<script>
    var myApp = myApp || {};  
    myApp.Urls = myApp.Urls || {};
    myApp.Urls.baseUrl = '@Url.Content("~")';   
    myApp.Urls.reportScoreUrl=  '@Url.Action("ReportScore","Tournaments")';  
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>

And in your PageSpecificExternalJsFile.js file, you can read it like 在您的PageSpecificExternalJsFile.js文件中,您可以像阅读

var myUrlToUser = myApp.Urls.reportScoreUrl;
alert(myUrlToUser);

or build using the base url. 或使用基本网址进行构建。

var myUrlToUser= myApp.Urls.baseUrl+"Tournaments/ReportScore";
alert(myUrlToUser);

The problem seems not in your javascript code but your controller action method (if it is indeed how it is written) 该问题似乎不在您的javascript代码中,而是在您的控制器操作方法中(如果确实如此,则是这样)

public async Task<ActionResult> ReportScore() { var a = "abc" } Your code block doesn't show any return statement, make sure your return value is awaited. public async Task<ActionResult> ReportScore() { var a = "abc" }您的代码块不显示任何return语句,请确保等待您的返回值。 ie return await "abc" return await "abc"

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

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