[英]Jquery Ajax send formdata to asp.net webpage (aspx.cs)
以下是我的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在服務器端未命中。 您能幫我我在代碼中遺漏的內容嗎? 提前致謝。
使用EnablePageMethods =“ True”將腳本管理器添加到頁面中
在C#中:
[WebMethod]
public static string SendData(DateTime date)
{//break point here
// code
return "return data";
}
在aspx中
<asp:ScriptManager ID="ScriptManagerMain"
runat="server"
EnablePageMethods="true"
ScriptMode="Release"
LoadScriptsBeforeUI="true">
</asp:ScriptManager>
在JavaScript中
PageMethods.SendDate(new Date(),function(response){
// success
});
並使用<asp:AsyncFileUpload ..異步上傳文件
<%@ 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>
也
protected void FileUploadComplete(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs(Server.MapPath("Uploads/") + filename);
}
和js
<script type = "text/javascript">
function uploadComplete(sender) {
$get("<%=lblMsg.ClientID%>").innerHTML = "File Uploaded Successfully";
}
function uploadError(sender) {
$get("<%=lblMsg.ClientID%>").innerHTML = "File upload failed.";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.