我想在我的mvc项目中使用ajax传递数据并触发conteroller
这是我的控制器
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
有人可以对此有所了解吗?
提前致谢
答案 0 :(得分: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");
}
})
})
答案 1 :(得分:0)
像这样传递记录data
,
url: 'File/Index?data=' + text, // Just make change here..
您只需要像这样更改传递给控制器URL
的{{1}}。
Action
答案 2 :(得分:0)
您错过了控制器中的void SaveDocument(FixedDocument document, string filePath)
{
var xps = new XpsDocument(
filePath, FileAccess.Write, CompressionOption.Maximum);
var writer = XpsDocument.CreateXpsDocumentWriter(xps);
writer.Write(document);
xps.Close();
}
标记。默认情况下,ASP.NET将尝试绑定URL中的简单参数,并仅绑定正文中的复杂参数。
试试这样:
[FromBody]
有关详细信息,请参阅this相关答案。