简体   繁体   中英

jQuery AJAX Call to Server Side Method Not Working

I am trying to call a server side method from a jQuery AJAX call but it is not working. Any help would be appreciated.

jQuery call is:

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

    $.ajax({
        type: "POST",
        url: "Ticket.aspx/AddAttachment",
        contentType: "application/json; charset=utf-8"
    }); 
});

Server Side code is:

    [WebMethod]
    public void AddAttachment()
    {
        string name = txtAttach.FileName;
        string strPath = ConfigurationManager.AppSettings["crmWorkspacesDir"].ToString() + txtTicketNum.Text + "\\";

        if (!Directory.Exists(strPath))
            Directory.CreateDirectory(strPath);

        txtAttach.SaveAs(strPath + name);

        DataTable oDT = (DataTable)ViewState["attachments"];
        DataRow oDR = oDT.NewRow();
        oDR["File"] = strPath + name;
        oDR["Size"] = new FileInfo(strPath + name).Length / 1000;
        oDT.Rows.Add(oDR);

        grdAttachments.DataSource =  oDT;
        grdAttachments.DataBind();

    }

It appears that the call is getting back to the Ticket.aspx page but not getting to the AddAttachment method. Does anyone see anything wrong with the jQuery? Thanks!

If you are writing a webmethod in code behind, it should be static. Change your web method like this

public static void AddAttachment()
{
    string name = txtAttach.FileName;
    string strPath = ConfigurationManager.AppSettings["crmWorkspacesDir"].ToString() + txtTicketNum.Text + "\\";

    if (!Directory.Exists(strPath))
        Directory.CreateDirectory(strPath);

    txtAttach.SaveAs(strPath + name);

    DataTable oDT = (DataTable)ViewState["attachments"];
    DataRow oDR = oDT.NewRow();
    oDR["File"] = strPath + name;
    oDR["Size"] = new FileInfo(strPath + name).Length / 1000;
    oDT.Rows.Add(oDR);

    grdAttachments.DataSource =  oDT;
    grdAttachments.DataBind();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM