我想使用 jQuery Ajax 将数据从 aspx 页面发送到 .cs Webmethod。我的html代码如下所示
<tr>
<td>
<input type="text" id="txtName">
</td>
</tr>
<tr>
<td>
<form action="" id="AttachmentForm1" enctype="multipart/form-data">
<input type="file" name="UploadFile1" id="txtUploadFile1" class="btn btn-sm" />
</form>
</td>
</tr>
我的javascript代码如下
function saveData() {
var file = $("#txtUploadFile1")[0].files[0];
$.ajax({
url: 'CCA_Form.aspx/SaveData',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Name: txtName, fileData: file }),
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});}
我的c#代码如下
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static bool SaveData(string Name, string[] fileData)
{
//Breakpoint
return true;
}
如何在 C# 中获取 Webmethod 中上传的文件?
提前致谢。
最佳答案
你需要使用 XMLHttpRequest
这家伙有一个非常好的教程。看看它是否对您有帮助:Click Here
或者
对于你上面的代码:
var filename = $("#txtUploadFile1").val();
$.ajax({
url: 'CCA_Form.aspx/SaveData',
type: 'POST',
enctype: 'multipart/form-data',
data: {file: filename},
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});}
关于javascript - 将文件从 JQuery Ajax 发送到 C# Webmethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43337418/