javascript jQUEry ajax调用asp.net webforms返回html页面而不是调用url中指定的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19264373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:55:38  来源:igfitidea点击:

jQUery ajax call to asp.net webforms returns html page instead of calling the specified method in the url

c#javascriptjqueryasp.netwebforms

提问by aleczandru

Hi I have very little experience with asp.net webforms but I have a situation where I have to execute an ajax call on the server every time the application is started or the page is changed.

嗨,我对 asp.net webforms 的经验很少,但我有一种情况,每次启动应用程序或更改页面时,我都必须在服务器上执行 ajax 调用。

Taking that into consideration I have added this method in the MasterPage.Master file:

考虑到这一点,我在 MasterPage.Master 文件中添加了这个方法:

 [WebMethod]
 public static void DeleteUnpostedDocumentsFromFileShare()
 {
     var ceva = "I was called";
 }

And added a brakepont to it so I can see when it is called.

并为其添加了一个刹车座,以便我可以看到它何时被调用。

This is the ajax call I am creating:

这是我正在创建的 ajax 调用:

$(document).ready(function() {
$.ajax({
    type: "POST",
    url: "/Masterpage.Master/DeleteUnpostedDocumentsFromFileShare",
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert(data);
    },
    error : function(data , data2 , data3) {
        alert(data);
    }
});

})

})

The problem is that this call returns the content of the html page instead of calling the method I needed.

问题是这个调用返回的是 html 页面的内容,而不是调用我需要的方法。

Can anyone tell me what I am doing wrong?

谁能告诉我我做错了什么?

回答by Somnath Kharat

I think u missed to return value to json from ur webmethod

我想你错过了从你的 webmethod 返回值到 json

    [WebMethod]
    public static string DeleteUnpostedDocumentsFromFileShare()
    {
        var ceva = "I was called";
        return ceva;
    }

Call Webmethod with json in asp.net

在asp.net中用json调用Webmethod

回答by iJade

I would suggest you write your ajax method to some other aspx page other than masterPage and remove the html content from that page.Use that page solely for writing web methods to be called via ajax. So your ajax web method page must have only page directives and nothing else.

我建议您将 ajax 方法写入 masterPage 以外的其他一些 aspx 页面,并从该页面中删除 html 内容。仅使用该页面来编写要通过 ajax 调用的 Web 方法。所以你的 ajax web 方法页面必须只有页面指令,没有别的。

And here is another way to call web method totally asp.net way, no need for using jquery

这是另一种完全用asp.net方式调用web方法的方法,不需要使用jquery

Calling C# function through Javascript (without Json)

通过 Javascript 调用 C# 函数(没有 Json)

Hope this helps

希望这可以帮助