2013-11-27 44 views
0

我有一個包含HTML表的div,我需要將該表傳遞給MVC3中的控制器。我正在嘗試使用ajax調用來傳遞表。調試時,我得到我的控制器到我的行爲聲明,但通過HTML表的值傳遞爲null。我是否發送正確。發送它有什麼問題。 請參考下面的鏈接,即使這一點,他們都面臨着同樣的問題 how to send html table from view to controller in mvc4在Ajax調用中向控制器發送數據時接收空值

下面是我的Ajax調用代碼:

$('#frmLogin').submit(function() { 

      var sendhtml = $('#divCashResultHolder').html(); 
      //alert(sendhtml); 
      $.ajax({ 
       url: '@Url.Action("ExportData", "CashCollection")',//action method url which defined in controller 
       type: 'POST', 
       data: { "htmlTable": sendhtml }, 
       dataType: 'json', 
       contentType: 'application/json; charset=utf-8', 
       async: true, 
       processData: false, 
       success: function(){ 
    console.log('success!!'); 
} 
      }); 

控制器代碼

[HttpPost] 
    public ActionResult ExportData(string htmlTable) 
    { 

      Response.Buffer = true; 
      Response.ContentType = "application/vnd.ms-excel"; 
      Response.AddHeader("Content-disposition", "attachment;filename=CashCollection_" + DateTime.Now.Ticks + ".xls"); 

     return View("CashCollection"); 
    } 

在控制器中我得到'字符串htmlTable'爲空值。我試圖將其設置爲HTML字符串類型沒有運氣。此外,我試圖發送數據:JSON.stringify(sendhtml)也沒有運氣。

+0

嘗試設置'processData'到TRUE; – Grundy

+0

好的,謝謝ü我得到的控制器值,但只有當div包含字符串值,然後,在控制器的參數就說明值。如果div包含表格,那麼它不會來控制器本身 – user1003054

回答

3

嘗試使用JSON.stringify

data: JSON.stringify({"htmlTable": sendhtml}); 
+0

沒有它沒有擊中控制器。它用這個數據命中控制器:{「htmlTable」:sendhtml},並且只有當div作爲字符串值時纔會被觸發。如果div包含表,它不會命中。在該div中它包含HTML表格。如果html表不存在,則顯示字符串「No informaton」 – user1003054

+0

檢查$('#divCashResultHolder')。val() –

+0

感謝您的幫助我使用javascript excel下載方法來下載excel文件。 – user1003054

0

這裏的問題是當數據即將控制器傳遞數據。它正在驗證。默認情況下,它們不允許發送html數據來控制。

爲了讓我們可以使用[ValidateInput(假)

那麼你的控制器看起來應該是這樣:

[HttpPost] 
[ValidateInput(false)] 
    public ActionResult ExportData(string htmlTable) 
    { 

      Response.Buffer = true; 
      Response.ContentType = "application/vnd.ms-excel"; 
      Response.AddHeader("Content-disposition", "attachment;filename=CashCollection_" + DateTime.Now.Ticks + ".xls"); 

     return View("CashCollection"); 
    } 

如果這是行不通的。那麼它可能是你的ajax方法問題。然後嘗試將您的數據作爲FormData發送。那麼你的AJAX方法應該是這樣的:

$('#frmLogin').submit(function() { 

      var sendhtml = $('#divCashResultHolder').html(); 
      //alert(sendhtml); 
     var fd = new FormData(); 
     fd.append("htmlTable", sendhtml); 

      $.ajax({ 
       url: '@Url.Action("ExportData", "CashCollection")',//action method url which defined in controller 
       type: 'POST', 
       data: fd, 
       enctype: 'application/form-data', 
       processData: false, 
       contentType: false, 
       success: function(){ 
         console.log('success!!'); 
       } 
      });