webmethod未被解雇

时间:2017-05-21 06:07:31

标签: javascript c# asp.net webmethod

我第一次尝试从javascript调用服务器端函数是不行的,因为webmethod没有被调用。

aspx文件包含一个bootstrap样式按钮;单击时,我需要向用户添加记录"收藏夹" list(在数据库中添加记录)。

页面继承自母版页,母版页包含:

<asp:ScriptManager runat="server" ID="ScriptManager1" EnablePageMethods="true" />

aspx页面有:

<script type="text/javascript">
function addFavorite(url, friendly) {debugger
    PageMethods.AddFavorite(url, friendly, onSuccess);
}
function onSuccess(result, userContext, methodName) {debugger
    alert(result);
}
</script>

<button type="button" class="btn btn-primary btn-xs" onclick="addFavorite('some_url', 'some firendly name');">
<i class="fa fa-heart-o" aria-hidden="true"></i>Favorites</button>

在代码背后:

[WebMethod]
public static string AddFavorite(string sURL, string sFriendlyName)
{
    // This is where I would add a record to a DB table, but for testing ...
    return sFriendlyName;
}

当我点击按钮时,它会点击addFavorites()并立即onSuccess并绕过web方法,它会在警告框中显示页面源(部分当然)。

我已经搜索过,似乎无法知道我做错了什么。所有示例都显示了我采取的相同步骤。

2 个答案:

答案 0 :(得分:0)

我可以在我的本地机器上重复这个。注意到脚本模块未在 web.config 模块部分中注册!

确保在web.config中包含脚本模块,以使其正常工作:

<system.webServer>
          <modules>
           <!-- *...other registered modules..* -->
           <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
           </modules>
    </system.webServer>

<强>更新

确保将FriendlyUrlSettings.AutoRedirectMode设置为Off,否则页面方法请求将返回401 UnAuthorized。代码应在RouteConfig中设置如下:

public static class RouteConfig  
{  
    public static void RegisterRoutes(RouteCollection routes)  
    {  
        var settings = new FriendlyUrlSettings();  
        settings.AutoRedirectMode = RedirectMode.Off;  
        routes.EnableFriendlyUrls(settings);  
    }  
}  

如果您想保留友好URL,请添加自己的友好URL解析器,该解析器继承自WebFormsFriendlyUrlResolver,如下所示:

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings, new WebMethodFriendlyUrlResolver());
    }
}

public class WebMethodFriendlyUrlResolver : WebFormsFriendlyUrlResolver
{
    public override string ConvertToFriendlyUrl(string path)
    {
        if (HttpContext.Current.Request.PathInfo != string.Empty)
        {
            return path;
        }
        else
        {
            return base.ConvertToFriendlyUrl(path);
        }
    }
}

如果启用了友好URL,则必须更新JavaScript回调函数以设置路径以明确包含.aspx扩展名:

function addFavorite(url, friendly) {  
        PageMethods.set_path(PageMethods.get_path() + '.aspx');  
        PageMethods.AddFavorite(url, friendly, onSuccess, onError);  
}  

答案 1 :(得分:0)

添加onFailure方法以查看它是否被点击。 (可能是必需的,但我不是肯定的。)编辑:我不认为这是必需的。我只是复制了你的代码,它在这里工作。

必须要问,只是为了确定:那些js函数是在脚本标记内? (我想是的,如果'成功'受到了打击。只需检查。)

再检查一次:使用所需语句后面的代码:using System.Web.Services;