2014-04-11 25 views
0

現在我在一個頁面上有多個表單,我想要刪除它。所以目前我正在這樣做。Ajax風格上傳等同於XmlHttpRequest文件上傳到MVC控制器?通過ajax上傳到MVC控制器解決了

JAVASCRIPT

$("button[id$='uploadfile']").click(function (evt) { 
     ////////////////////////////////////////////////////// 
     // This code block works 
     alert("upload file"); 
     var file1 = $('#csvIdentifierFileBase').val(); 
     var formData = new FormData(); 
     var opmlFile = $('#csvIdentifierFileBase')[0]; 
     formData.append("opmlFile", opmlFile.files[0]); 
     var xhr = new XMLHttpRequest(); 
     xhr.open('POST', 'alt/Import'); 
     xhr.send(formData); 
     xhr.onreadystatechange = function() { 
      if (xhr.readyState == 4 && xhr.status == 200) { 
       alert(xhr.responseText); 
      } 
     }; 
     ////////////////////////////////////////////////////// 

     ////////////////////////////////////////////////////// 
     // This code block does not 
     $.ajax({ 
      type: 'POST', 
      url: 'alt/Import', 
      data: formData, 
      enctype: 'multipart/form-data', 
      //cache: false, 
      //contentType: false, 
      //processData: false, 
      success: function (result) { 
       alert(result.success); 
      }, 
      error: function (a, b, c) { 
       alert("An error has occurred."); 
      } 
     }); 

HTML

 <div class="col-md-12"> 
      <input type="file" name="csvIdentifierFileBase" id="csvIdentifierFileBase"/> 
      <button id="uploadfile" name="action" value="Import" >Import</button> 
     </div> 

控制器

[System.Web.Http.HttpPost] 
    public ActionResult Import()//HttpPostedFileBase csvIdentifierFileBase) 
    { 
     HttpResponseMessage result = null; 
     HttpPostedFileBase file = Request.Files[0]; //Uploaded file 
    } 

在不改變任何東西BESI des javscript調用這個控制器方法,並使用XmlHttpRequest工作正常,有沒有辦法切換到jquery/ajax風格的調用,所以我不依賴於XmlHttpRequest對象,仍然有調用控制器?我正在尋找一個本地解決方案,而不是另一種類型的插件......這可能嗎? 也無法將輸入和按鈕封裝在AJAX.BeginForm標記中,因爲我試圖消除一個頁面上的表單數量。

+0

我剛剛發佈了答案http://stackoverflow.com/questions/23007332/how-to-upload-file-via-mvc4-and-get-json-response/23008287#23008287也看到這個http:///stackoverflow.com/questions/19042116/ajax-beginform-in-mvc-to-upload-files/19044689#19044689 –

+0

我不能使用Ajax.beginform,因爲我最終會得到一個表單內的表單,不起作用。這就是爲什麼我在沒有表單標籤的情況下進行上述操作。我需要能夠在沒有形式標籤的情況下做你在該帖子上做的Ashwini。 – DRobertE

回答

1

希望這會幫助別人,因爲我在這花了相當長的一段時間。以下是如何通過$ .ajax發佈文件,而無需任何額外的插件,並且無需在html視圖中使用Ajax.BeginForm標籤。

JAVASCRIPT

$("button[id$='uploadfile']").click(function (evt) { 
    alert("upload file"); 
    // relatively irrelevant name used here but is not what model binder uses in MVC 
    var file_data = $("#csvIdentifierFileBase").prop("files")[0]; // Getting the properties of file from file field 
    var form_data = new FormData();     // Creating object of FormData class 
    // THIS IS IMPORTANT, THE NAME HERE **"file"** IS WHAT THE MODEL BINDER USES IN MVC CONTROLLER 
    form_data.append("file", file_data);   // Appending parameter named file with properties of file_field to form_data 
    //form_data.append("user_id", 123);    // Adding extra parameters to form_data 
    $.ajax({ 
     url: "alt/Import", 
     dataType: 'script', 
     cache: false, 
     contentType: false, 
     processData: false, 
     data: form_data,       // Setting the data attribute of ajax with file_data 
     type: 'post' 
    }); 
}); 

HTMLNO FORM標記NO PLUGGINS

  // name and id of input type file relatively irrelevant 
     <div class="col-md-12"> 
      <input type="file" name="csvIdentifierFileBase" id="csvIdentifierFileBase"/> 
      <button id="uploadfile" name="action" value="Import" >Import</button> 
     </div> 

CONTROLLER

[System.Web.Http.HttpPost] 
    public ActionResult Import(HttpPostedFileBase file) // THIS VAIRABLE NAME HAS TO BE THE SAME AS WHAT IS PASSED IN VIA THE SCRIPT FOR FORM DATA 
    { 
     HttpResponseMessage result = null; 
     HttpPostedFileBase file = Request.Files[0]; //Uploaded file JUST A SECOND WAY TO ACCESS THE SAME INFORMATION THAT IS COMING IN AS HttpPostedFileBase file 
    } 

無論其這裏的GIT FORMDATA()不支持IE所以這種方法不適用於IE

支持信息化工作可以在這裏找到 http://blog.w3villa.com/websites/uploading-filesimage-with-ajax-jquery-without-submitting-a-form/

IE。除上述

HTML

 <div class="col-md-12"> 
      <input type="file" name="csvIdentifierFileBase" id="csvIdentifierFileBase"/> 
      <button id="uploadfile" name="action" value="Import" >Import</button> 
     </div> 

JAVASCRIPT

$("button[id$='uploadfile']").click(function (evt) { 
    evt.preventDefault(); 
    var $newForm = $('<form>', { 
     'action': 'alt/Import', 
     'method': 'post', 
     'enctype': 'multipart/form-data', 
     'target':'_top' 
//dynamically appending the input type file to the dynamically generated form and it MUST be appended to the page to work. "appendTo(body") submit then remove 
}).append($("#csvIdentifierFileBase")).appendTo('body').submit().remove(); 

});

現在NAME MATTER

DOES由於輸入元件被動態添加到形式名稱確實有用於模型粘結劑工作匹配控制器方法PARAM NAME。

[System.Web.Http.HttpPost] 
public ActionResult Import(HttpPostedFileBase csvIdentifierFileBase) 
{ 

} 

基本上沒有什麼不同,然後有一個表單標籤周圍的輸入,這是我試圖避免的情況。我這樣做的原因,以及爲什麼我試圖避免在一個頁面上的多個表單是因爲我在一個情況下,我會有嵌套的表單標籤,將無法正常工作。

+0

這是完美的!這正是我正在尋找的!我也不想使用插件或更多的表單。非常感謝發佈這個。 – FLAdmin

相關問題