2014-10-30 73 views
0

我試圖發佈一些數據以及上傳的文件。首先,我嘗試將所有希望在服務器端檢索的數據作爲參數傳遞。即使我設法正確地檢索參數「模式」的值。我從來沒有收到參數「文件」的值。我不知道爲什麼?在服務器端訪問ajax帖子表單數據

以下是我的代碼:

控制器:

public ActionResult ReadFromExcel(HttpPostedFileBase file, bool Mode) 
{ 
    // file is always null 
    // Mode receives the correct values. 
} 

腳本:

$(document).ready(function() { 
$("#ReadExcel").click(function() { 

    var overwritefields = $("#overwritefields").is(":checked"); 


    $.ajax({ 
     type: "POST", 
     url: 'ReadFromExcel', 
     data: '{"file":"' + document.getElementById("FileUpload").files[0] + '","Mode":"' + overwritefields + '"}', 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     processData: false, 
     success: function (response) { 
      // Refresh data 

     }, 
     error: function (error) { 
      alert("An error occured, Please contact System Administrator. \n" + "Error: " + error.statusText); 
     }, 
     async: true 
    }); 
}); 

然後我試圖通過Request.File訪問文件的[0],這是成功的高達一定程度上。但是,我如何檢索其他表單數據的值,例如「模式」?

以下是我的代碼:

控制器:

public ActionResult ReadFromExcel() 
{ 
    var file = Request.Files[0]. 
    // file contains the correct value. 
    // Unable to retrieve mode value though. 
} 

腳本:

$(document).ready(function() { 
$("#ReadExcel").click(function() { 

    var formData = new FormData(); 
    formData.append("FileUpload", document.getElementById("FileUpload").files[0]); 


    var overwritefields = $("#overwritefields").is(":checked"); 
    formData.append("Mode", overwritefields); 


    $.ajax({ 
     type: "POST", 
     url: 'ReadFromExcel', 
     data: formData, 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     processData: false, 
     success: function (response) { 
      // Refresh data 

     }, 
     error: function (error) { 
      alert("An error occured, Please contact System Administrator. \n" + "Error: " + error.statusText); 
     }, 
     async: true 
    }); 
}); 

以下是我的觀點:

@model IPagedList<Budget> 

@{ 
ViewBag.Title = "Import Budget Line Items From Excel"; 
var tooltip = new Dictionary<string, object>(); 
tooltip.Add("title", "Click to import budget line items from Excel"); 

int pageSize = 10; 
string sortname = "ItemCode"; 
string sortorder = "asc"; 
string filter = ""; 
bool hasFilter = false; 
if (Session["BudgetImportGridSettings"] != null) 
{ 
    // 
    // Get from cache the last page zise selected by the user. 
    // 
    Impetro.Models.Grid.GridSettings grid = (Impetro.Models.Grid.GridSettings)Session["BudgetImportGridSettings"]; 
    pageSize = grid.PageSize; 
    sortname = grid.SortColumn; 
    sortorder = grid.SortOrder; 
    filter = grid.HasFilter ? grid.FilterString : ""; 
    hasFilter = grid.HasFilter && grid.Filter.rules.Count > 0; 
} 

} 


<h2>@ViewBag.Title</h2> 


<br style="clear: both;" /> 
<input type="file" id="FileUpload" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" /> 
<span class="buttonspan backtolist" id="ReadExcel" title="Click to import budget line items from Excel"><a href="#" title="Click to import budget line items from Excel">Import</a></span> 
<br style="clear: both;" /> 
<br style="clear: both;" /> 
<input type="checkbox" id="overwritefields" title="Overwrite other fields with imported non-blank data" class="chkclass" value=false /> 

<br style="clear: both;" /> 
<br style="clear: both;" /> 

@Html.Partial("_BudgetImportGrid") 
<input type="hidden" value="@ViewBag.BudgetType" id="IntBudgetType" /> 
+0

看到我的回答,讓我知道如果你想讓我建議其他方式.. h – Mzn 2014-10-30 08:52:41

+0

我不能像你那樣使用FormData ...!所以我用FileReader – Mzn 2014-10-30 12:34:09

回答

1

一個簡單的方法來做到這一點是隻是爲了添加bool mode到動作方法:

public ActionResult ReadFromExcel(bool Mode) 
{ 
    //Use the selected Mode... 

    var file = Request.Files[0]. 
    // file contains the correct value. 
    // Unable to retrieve mode value though. 
} 
+0

如何將Mode參數傳遞給服務器端? – ecasper 2014-10-30 10:43:09

+0

通過使用ASP .NET MVC框架! ;)綁定是由框架自動完成的:它查找請求(從QueryString,表單數據,ajax數據等進行搜索)... – Mzn 2014-10-30 11:15:10

+0

因此,只需將您的模式與ajax數據包括在一起即可。 – Mzn 2014-10-30 11:15:59

0

我希望你能使用HTML5文件讀取器API。以下解決方案使用它:

我從頭開始構建您的場景以確保我的建議有效。

總結:

  1. bool mode作爲動作方法參數。它使用查詢字符串提供給服務器。
  2. 作爲二進制文件作爲請求主體的一部分上傳的文件。二進制數據是使用FileReader HTML5 API獲取的。這是HTML5的一部分,如果你可以替換它,那麼你可能會得到HTML5的依賴。
  3. AJAX是一個POST請求!

使用下面的JavaScript:

$(function(){ 
    $("#upload").click(function() { 
     var overwritefields = $("#overwritefields").is(":checked"); 

     var r = new FileReader(); 
     r.onload = function() { 
      $.ajax({ 
       type: "POST", 
       url: 'UploadFileWithBoolean?mode=' + overwritefields, 
       data: r.result, 
       contentType: 'application/octet-stream', 
       processData: false, 
       success: function (d) { 
        console.log("ok"); 
        console.log(d); 
       }, 
       error: function (d) { 
        console.log("fail"); 
        console.log(d); 
       }, 
       async: true 
      }); 
     }; 
     r.readAsBinaryString(document.getElementById("FileUpload").files[0]); 
    }); 
}); 

控制器方法:

[HttpPost] 
public ActionResult UploadFileWithBoolean(bool mode) 
{ 
    //your file is now in Request.InputStream 
    return Json(new { message = "mode is " + mode.ToString(), filesize = Request.InputStream.Length }); 
} 

讓我知道,如果這有助於與否。謝謝