2016-08-02 136 views
1

我特林使用AJAX和觸發conteroller數據掠過我的MVC項目JQuery/MVC/ajax如何使用ajax發佈數據到控制器?

這是我的控制器

public class FileController : Controller 
{ 
    [HttpPost] 
    public ActionResult Index(string data) 
    { 
     return View(); 
    } 
} 

這是JS

$('#getmessage').on('click', function() { 
     var text = ''; 
     $('#discussion>li').each(function() { 
      text += $(this).text(); 
      text += '\n' 
     }) 
     console.log(text) 

     $.ajax({ 
      url: 'http://localhost:22828/File/Index', 
      type: 'POST', 
      data: text, 
      success: function (result) { 
       console.log("data sended"); 
      } 
     }) 
    }) 

我需要通過文本控制器,但在我的控制器中,我得到了NULL
有人可以請說明一點嗎?
在此先感謝

回答

2

更改您的Javascript來此:

$('#getmessage').on('click', function() { 
     var text = ''; 
     $('#discussion>li').each(function() { 
      text += $(this).text(); 
      text += '\n' 
     }) 
     console.log(text) 

     $.ajax({ 
      url: 'http://localhost:22828/File/Index', 
      type: 'POST', 
      data: { data: text }, // This is all you have to change 
      success: function (result) { 
       console.log("data sended"); 
      } 
     }) 
    }) 
+0

控制器仍然獲得數據= null – barak

+0

當你做'console.log(文本)',有什麼嗎?另外請記住用';'關閉你的線條,這樣可以讓每個人都更容易知道線路的起點和終點。 – Morgs

+0

是在我的console.log我得到的文字 – barak

0

傳遞記錄data這樣,

url: 'File/Index?data=' + text, // Just make change here.. 

你只需要改變要傳遞給控制器​​的URLAction是這樣的。

$('#getmessage').on('click', function() { 
    var text = ''; 
    $('#discussion>li').each(function() { 
     text += $(this).text(); 
     text += '\n' 
    }) 
    console.log(text) 

    $.ajax({ 
     url: 'File/Index?data=' + text, // Just make change here.. 
     type: 'POST', 
     data: text, 
     success: function (result) { 
      console.log("data send"); 
     } 
    }) 
}) 
+0

仍然無法正常工作,在我的控制器中獲取text = null – barak

+0

通過將'debugger'放入其中,首先在JavaScript中檢查您的文本。並通過把靜態值檢查... –

0

您錯過了控制器中的[FromBody]標記。默認情況下,ASP.NET將嘗試綁定來自URL的簡單參數,並且僅從主體中複雜。

試試這樣說:

public class FileController : Controller 
{ 
    [HttpPost] 
    public ActionResult Index([FromBody] string data) 
    { 
     return View(); 
    } 
} 

欲瞭解更多詳情,請參閱相關的this答案。

相關問題