2015-05-14 21 views
1

我有具有文本框和下拉菜單等的y個的x個一個WebForm 我使用這個代碼發送數據在服務器上的WebMethod:如何將文件與其他字段的數據一起發送到webmethod是使用jquery ajax調用的asp.net?

$.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); 
    } 
}); 

現在的問題是,我還希望包括文件附件在這個表格上。 如何將文件添加到的data:方法? 我不想使用外部插件等,除非絕對必要。

可以說,我修改我的數據對象,看起來像這樣:

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

將將WebMethod armument什麼樣子? 例如,假設它現在看起來像這樣: [WebMethod] public static string SubmitBid(string id, string bidamt.....)

回答

0

你可以嘗試類似這樣的事情。您可能需要操作內容類型。

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); 
    } 
}); 
+0

什麼是webmethod中的參數類型?像現在一樣它看起來像:[WebMethod]公共靜態字符串SubmitBid(字符串id,字符串bidamt .....)' 我有一個更新我的問題 – Arbaaz

0

無法發送文件作爲application/json; charset=utf-8到服務器,所以我建議你使用application/x-www-form-urlencoded作爲contentType和下面還dataFormData

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

什麼是webmethod中的參數類型?像現在一樣,它看起來像:[WebMethod] public static string SubmitBid(string id,string bidamt .....)' – Arbaaz

+0

試試這個,'[WebMethod] public static string SubmitBid(string id,string bidamt, HttpPostedFile文件)'。如果你有這個問題,那麼你可以使用'Context.Request.Files'從請求'context'中提取文件。 – Madhu

+0

似乎沒有工作。我無法調用webmethod本身。 – Arbaaz

相關問題