Asp.net mvc 将数据从js发送到控制器

Asp.net mvc 将数据从js发送到控制器,asp.net-mvc,Asp.net Mvc,我有一个ajax: function sendData() { var question = (document.getElementById('question').value).toString(); var c = (document.getElementById('c').value).toString(); $.ajax({ url: '/Home/InsertData', type: 'POST', data:

我有一个ajax:

function sendData() {
    var question = (document.getElementById('question').value).toString();
    var c = (document.getElementById('c').value).toString();
    $.ajax({
        url: '/Home/InsertData',
        type: 'POST',
        data: {question:question, c:c},
        // data: {},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function () {
            alert('suc');
        },
        error: function (error) {
            alert('error');
        }
    });
}
在my
HomeController
中,我具有以下功能:

[HttpPost]
public void InsertData(string question, string c)
//public void InsertData()
{
    this.insertDataToCustomers(question, c);

}
当我运行它时,我得到一个错误:

POST http://localhost:2124/Home/InsertData 500 (Internal Server Error) 
如果我没有在
InsertData
函数中请求输入值,也没有在
ajax
中发送数据,那么它可以工作。为什么我不能将数据发送到
InsertData
函数

p.s.
question
c

谢谢大家!

删除此项:

contentType: 'application/json; charset=utf-8',
您没有向服务器发送任何JSON,因此请求的内容类型不正确。您正在发送
应用程序/x-www-form-urlencoded
请求

因此:

代码的另一个问题是指出了
数据类型:“json”
,这意味着您希望服务器返回json,但控制器操作没有返回任何内容。这只是一种无效的方法。在ASP.NET MVC中,控制器操作应返回操作结果。因此,如果您想返回一些JSON(例如)来指示操作的状态,您可以使用以下命令:

[HttpPost]
public ActionResult InsertData(string question, string c)
{
    this.insertDataToCustomers(question, c);
    return Json(new { success = true });
}
当然,您可以返回任意对象,该对象将被JSON序列化,并且您可以在
success
AJAX回调中访问它

[HttpPost]
public ActionResult InsertData(string question, string c)
{
    this.insertDataToCustomers(question, c);
    return Json(new { success = true });
}