Jquery Ajax将formdata发送到asp.net网页(aspx.cs)

时间:2017-05-03 03:23:57

标签: c# jquery asp.net ajax

以下是我的ajax请求

function sendData() {
    var formdata = new FormData();
    var fileUpload = $("#txtUploadFile").get(0);
    var files = fileUpload.files;   
    for (var i = 0; i < files.length; i++) {
        formdata.append(files[i].name, files[i]);
        }
    formdata.append("PaymentDate", new Date());
    $.ajax({
        url: 'CCA_Form.aspx/SendData',
        type: 'POST',
        data: formdata,
        contentType: false,
        processData: false,
        success: function () {
            alert("Data Added Successfully");
        },
        error: function () {
            alert("Error while inserting data");
        }
    });
}

我的服务器方法就像这样

    [WebMethod]
    public static string SendData()
    {//break point here
        // code
        return "return data";
    }

ajax方法始终显示成功消息和webmethod未在服务器端点击。你能帮我解决一下我错过的代码吗?  提前谢谢。

1 个答案:

答案 0 :(得分:0)

使用EnablePageMethods =&#34; True&#34;

将脚本管理器添加到您的页面中

在C#中:

My Computer

在aspx中

  [WebMethod]
  public static string SendData(DateTime date)
  {//break point here
      // code
      return "return data";
  }

在javascript中

  <asp:ScriptManager ID="ScriptManagerMain"
        runat="server"
        EnablePageMethods="true" 
        ScriptMode="Release" 
        LoadScriptsBeforeUI="true">
  </asp:ScriptManager>

并使用&lt; asp:AsyncFileUpload ..来异步上传文件

 PageMethods.SendDate(new Date(),function(response){
    // success
 });

另外

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="xc" %>

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<xc:AsyncFileUpload OnClientUploadError="uploadError"
    OnClientUploadComplete="uploadComplete" runat="server"
    ID="AsyncFileUpload1" Width="400px" UploaderStyle="Modern"
    OnUploadedComplete = "FileUploadComplete"
  />
 <asp:Label id="lblMsg" runat="server" />
</form>

和js

protected void FileUploadComplete(object sender, EventArgs e)
{
    string filename  = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
     AsyncFileUpload1.SaveAs(Server.MapPath("Uploads/") + filename);   
}