C# 我无法使我的WebMethod在ASP.NET中工作
我目前正在用C#创建一个网页,作为一个学校项目。 我已在文件中创建了WebMethod: Default.aspx.csC# 我无法使我的WebMethod在ASP.NET中工作,c#,jquery,asp.net,ajax,webmethod,C#,Jquery,Asp.net,Ajax,Webmethod,我目前正在用C#创建一个网页,作为一个学校项目。 我已在文件中创建了WebMethod: Default.aspx.cs [WebMethod] public static string MyWebMethod() { return string.Format("Hello From Server"); } 以及文件中的Ajax调用: Default.aspx <script type="text/javascript"&g
[WebMethod]
public static string MyWebMethod()
{
return string.Format("Hello From Server");
}
以及文件中的Ajax调用:
Default.aspx
<script type="text/javascript">
function test() {
jQuery.ajax({
type: "POST",
url: "Default.aspx/MyWebMethod",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(dd, status) {
alert('Success' + JSON.stringify(dd) + " status: " + JSON.stringify(status));
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
</script>
<input type="button" value="click me" onclick="test();" />
但在寻找了几个小时的解决方案后,我几乎放弃了。
当我尝试一个修复程序时,它显然已经为其他人解决了这个错误,但它仍然不适用于我
有人知道怎么做吗
感谢您抽出时间您应该更改jquery ajax的url路径:
url: "Default.aspx/MyWebMethod",
您不需要将.aspx添加到它,只需要添加到页面。假设您的方法是在名为
“视图”
的文件夹中的默认.aspx
文件的代码中定义的,那么您的url应该是这样的:
url: "/Views/Default.aspx/MyWebMethod",
注释掉App_Start文件夹的Routeconfig中的AutoRedirectMode将解决此问题
// settings.AutoRedirectMode = RedirectMode.Permanent;
是的,很抱歉。那只是我试过的。这两种方式都不起作用。似乎您在错误消息中找到了答案。这个项目中是否启用了FormsAuth、WindowsAuth或其他功能?我真的不知道。我刚刚在VS2013中创建了一个新的WinForms项目,并开始在模板中编码。它有“默认”、“关于”、“联系”页面。如何确定是否启用了FormsAuth或WindowsAuth?最后。我找到了解决办法!在RouteConfig.cs文件中,必须取消对行设置的注释。AutoRedirectMode=RedirectMode.Permanent;所以它应该是://settings.AutoRedirectMode=RedirectMode.Permanent;这帮我解决了!(显然,当你是新手时,你不能回答自己的问题)此外,你的回答不太可能是JSON字符串。取而代之的是XML。您应该将返回类型设置为void,然后手动转换为JSON(使用诸如的库),并使用
response.write()
直接写入响应。请记住设置内容类型。
// settings.AutoRedirectMode = RedirectMode.Permanent;