Shaggy
Shaggy

Reputation: 5790

calling code behind c# method from jquery ajax

i am trying to call code behind method from jquery ajax call but it doesnt hit break point on that methhod. what i am missing ?

js

$('#btn_Submit').click(function () {
    $.ajax({
            url: 'ajaxExecute.aspx/CAO2',
            data: 'Guardian=' + $('#txtGuardianName').val() + '&CIFID=' + $('#txtCIFID').val() + '&EmploymentType=' + encodeURIComponent($('#cmbEmploymentType').val()) + '&NatureIncome=' + encodeURIComponent($('#cmbIncomeNature').val()) + '&Occupation=' + encodeURIComponent($('#cmbOccupation').val()),
            cache: false,
            context: document.body,
            type: 'POST',
            success: function (response) {

            }
        });
}

ajaxExecute.aspx.cs

public partial class ajaxExecute : System.Web.UI.Page
{
    [WebMethod]
    public static void CAO2(string Guardian, string CIFID, string EmploymentType, string NatureIncome, string Occupation)
    {
            //Some Code
        //No breakpoint hit here
    }

    protected void Page_Load(object sender, EventArgs e)
    {
            //Some Code
        // Got Breakpoint here
    }
}

Upvotes: 0

Views: 14361

Answers (3)

Mikhail Timofeev
Mikhail Timofeev

Reputation: 2169

Try to send data as JSON:

$('#btn_Submit').click(function () {

   var request = {
     Guardian : $('#txtGuardianName').val(),
     CIFID : $('#txtCIFID').val(),
     EmploymentType : encodeURIComponent($('#cmbEmploymentType').val(),
     NatureIncome : encodeURIComponent($('#cmbIncomeNature').val()),
     Occupation : encodeURIComponent($('#cmbOccupation').val()
   };    

   var strRequest = JSON.stringify(request);  

   $.ajax({
            url: 'ajaxExecute.aspx/CAO2',
            data: strRequest,
            dataType: "json",
            contentType: "application/json",  
            cache: false,
            context: document.body,
            type: 'POST',
            success: function (response) {

            }
        });
   }

Upvotes: 1

Zaphod
Zaphod

Reputation: 1482

try to Json-ify you input data.
something like (not tested): data: JSON.stringify({ Guardian: $('#txtGuardianName').val(), CIFID: $('#txtCIFID').val() ... })

Upvotes: 1

Damith
Damith

Reputation: 63065

try below

var dataString = JSON.stringify({ 
    Guardian : $('#txtGuardianName').val(), 
    CIFID : $('#txtCIFID').val(), 
    EmploymentType : encodeURIComponent($('#cmbEmploymentType').val(),
    NatureIncome : encodeURIComponent($('#cmbIncomeNature').val()),
    Occupation : encodeURIComponent($('#cmbOccupation').val()
});

$.ajax({
    type: "POST",
    url: "ajaxExecute.aspx/CAO2",
    data: dataString,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
       alert("Success");
    }
});

Upvotes: 1

Related Questions