【问题标题】:Call WebMethod from JQuery with Parameter in C#使用 C# 中的参数从 JQuery 调用 WebMethod
【发布时间】:2019-02-02 20:00:40
【问题描述】:

我有以下 HTML 超链接,我想在点击时在 jQuery 中调用它

<a href="#" data-toggle="dropdown" id="notID" class="dropdown-toggle f-s-14">
                <i class="fa fa-bell"></i>
                <span runat="server" id="notCount" class="label">5</span>
            </a>

当我点击超链接时,会执行以下代码

<script src="assets/plugins/jquery/jquery-1.9.1.js"></script>
<script>
    $(document).ready(function () {
        $("#notID").click(function () {

            var uID = '<%=Session["userID"].ToString() %>'

            $.ajax({
                url: 'TaskService.asmx/updateNotRead',
                data: '{userID: "' + uID + '"}',
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json'
            });
            return false;
        });
    });
</script>

在 webservice 文件中,我编写了以下 C# 代码,其中包含我从上面的 jQuery 调用的 webmethod 的定义。

[WebMethod]
    public void updateNotRead(string userID)
    {
        u.updateNotReadStatus(userID);
    }

当我调用网络服务时,我在浏览器中收到以下消息

System.InvalidOperationException: Missing parameter: userID.
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

那么我怎样才能给 web 方法提供 userID 参数呢?

【问题讨论】:

    标签: c# jquery webmethod


    【解决方案1】:

    试试这样:

    var uID = '<%=Session["userID"].ToString() %>';
    $.ajax({
        url: 'TaskService.asmx/updateNotRead',
        data: "{userID : '" + uID + "'}",
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json'
    });
    

    【讨论】:

      【解决方案2】:
      data: '{userID: "' + uID + '"}',
      

      应该是:

      data: "{userID : '" + uID + "'}",
      

      【讨论】:

        【解决方案3】:

        我认为您的问题出在数据参数上。

        data:{userID:uID},
        

        而不是

        data: '{userID: "' + uID + '"}',
        

        我会使用一个对象para来包含参数,这样可以让代码更简单。

        var uID = '<%=Session["userID"].ToString() %>';
        var para = {userID:uID};
        $.ajax({
            url: 'TaskService.asmx/updateNotRead',
            data: para,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json'
        });
        

        【讨论】:

          猜你喜欢
          • 2018-12-14
          • 1970-01-01
          • 2014-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-13
          • 1970-01-01
          相关资源
          最近更新 更多