使用jQuery调用WebMethod

时间:2015-02-12 11:53:54

标签: c# jquery web-services

您好我想传递jQuery中的值并将这些值分配给方法中使用的类模型。

以下是我的剧本:

$(document).ready(function(){
        $('#BtnSubmit').click(function () {
            var CollegeName = $('#TxtCollegeName').val();
            var CollegeAddress = $('#TxtCollegeAddress').val();
            var pageUrl = '<%=ResolveUrl("~/AddNewCollege.aspx/CreateCollegeData")%>';
            $.ajax({
                type: 'Post',
                url: pageUrl,
                data: JSON.stringify({ "CollegeName": CollegeName, "CollegeAddress": CollegeAddress}),
                dataType: 'text',
                contentType: 'application/json; charset=utf-8',
                success: function (response) {
                    $('#lblResult').html('Inserted Successfully');                        
                },
                error: function () {
                    alert("An error occurred.");
                }
            });
        });
    });

以下是我的Csharp方法:

[WebMethod]
    public static string CreateCollegeData(CollegeDetails collegeDetails)
    {
        CollegeDAL obj = new CollegeDAL();
        bool b = obj.InsertCollegeDetails(collegeDetails);
        return "success";
    }

但调试器无法调用Web方法。每次出现以下消息时:

enter image description here

2 个答案:

答案 0 :(得分:1)

提前尝试声明您的对象:link

答案 1 :(得分:1)

我有另一个解决方案。

 $('#BtnSubmit').click(function () {
            var collegeDetails = {};
            collegeDetails.CollegeName = $('#TxtCollegeName').val();
            collegeDetails.CollegeAddress = $('#TxtCollegeAddress').val();               
            $.ajax({
                type: 'POST',
                url: 'AddNewCollege.aspx/CreateCollegeData',
                data: "{collegeDetails:" + JSON.stringify(collegeDetails) + "}",
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (response) {
                    $('#lblResult').html('Inserted Successfully');
                    $('#TxtCollegeName').val('');
                    $('#TxtCollegeAddress').val('');
                },
                error: function () {
                    alert("An error occurred.");
                }
            });
        });