简体   繁体   English

我如何使用jquery ajax调用将文件以及其他字段的数据发送到asp.net的web方法?

[英]How can I send files along with other field's data to webmethod is asp.net using jquery ajax call?

I have a webform which has x number of textboxes and y number of dropdowns etc I am using this code to send data to webmethod at the server: 我有一个Web表单,其中有x个文本框和y个下拉列表等,我正在使用此代码将数据发送到服务器上的webmethod:

$.ajax({
    type: "POST",
    url: "SupplierMaster.aspx/RegisterSupplier",
    data: JSON.stringify({
        id: $('#txtbidderid').val(),
        bidamt: $('#txtbidamt').val()
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    success: function (data, status) {
        alert(data.d);
    },
    failure: function (data) {
        alert(data.d);
    },
    error: function (data) {
        alert(data.d);
    }
});

Now the problem is that I also want to include file attachments on this form. 现在的问题是,我也想在此表单上包括文件附件。 How do I add the files to data: of $.ajax method? 如何将文件添加到$.ajax方法的data:中? I do not want to use external plugins etc unless absolutely necessary. 除非绝对必要,否则我不想使用外部插件等。

Lets say I modify my data object to look like this : 可以说我将数据对象修改为如下形式:

var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );

What would the webmethod armument look like? 网络方法装备是什么样的? For example lets suppose it looks like this as of now: [WebMethod] public static string SubmitBid(string id, string bidamt.....) 例如,假设现在看起来像这样: [WebMethod] public static string SubmitBid(string id, string bidamt.....)

You can try something like this. 您可以尝试这样。 You may need to manipulate content type. 您可能需要操纵内容类型。

var dataToSend = new FormData();    
dataToSend.append( 'file', input.files[0] );

$.ajax({
  url: "SupplierMaster.aspx/RegisterSupplier",
  data: dataToSend,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

You cannot send file as application/json; charset=utf-8 您不能将文件作为application/json; charset=utf-8发送application/json; charset=utf-8 application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below. application/json; charset=utf-8到服务器,因此我建议您使用application/x-www-form-urlencoded作为contentType并将data作为FormData如下所示。

            $.ajax({
            url: "SupplierMaster.aspx/RegisterSupplier",
            type: 'POST',
            data: new FormData(formElement),//Give your form element here
            contentType: false,
            processData: false,
            success: function () {
                //do success
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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