从控制器中的ajax POST空接收参数+在firebug MVC 4中传递参数

tho*_*lau 3 asp.net-mvc jquery asp.net-ajax asp.net-mvc-4

我已经看过网,弄清楚我的错误是什么.我发现我尝试的所有建议都没有任何成功.我在控制器中访问httppost动作,但参数保持为空.

AJAX功能

var dataPost = { 'id': id, 'val': val };
                    debugger;
                    $.ajax({
                        type: 'POST',
                        url: '/Extensions/UpdateJson',
                        data: dataPost ,
                        contentType: 'json',
                        success: function () {
                            alert("succes");
                        },
                        error: function () {
                            alert("error");
                        }
                    });
Run Code Online (Sandbox Code Playgroud)

在调试DataPost时填充.

调节器

    [HttpPost]
    public ActionResult UpdateJson(string id, string val)
    {
        //do stuff
        return Json(true);
    }
Run Code Online (Sandbox Code Playgroud)

我在控制器中使用的参数与我的Ajax函数中的名称相同.传递的格式是json,我也尝试使用以下方法填充数据:

var dataPost = { 'id': 'id', 'val': 'val' };
Run Code Online (Sandbox Code Playgroud)

但这没有任何区别.我也尝试过使用类,比如 - >

public class ScheduleData
{
    public string id { get; set; }
    public string val { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

调节器

    public ActionResult UpdateJson(ScheduleData data)
    {//Do something}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.提前致谢

Dar*_*rov 6

传递的格式是json

一点都不.您没有发送任何JSON.你做的是

data: { 'id': id, 'val': val }
Run Code Online (Sandbox Code Playgroud)

但正如文档清楚地解释这是使用$.param函数,而函数反过来使用application/x-www-form-urlencoded编码.

所以contentType: 'json'从$ .ajax调用中删除此属性.

或者,如果你真的想发送JSON,那么这样做:

var dataPost = { 'id': id, 'val': val };
$.ajax({
    type: 'POST',
    url: '/Extensions/UpdateJson',
    data: JSON.stringify(dataPost),
    contentType: 'application/json',
    success: function () {
        alert("succes");
    },
    error: function () {
        alert("error");
    }
});
Run Code Online (Sandbox Code Playgroud)

需要注意的事项:

  • 的使用JSON.stringify(dataPost),以确保您要发送一个JSON字符串到服务器
  • contentType: 'application/json' 因为这是正确的Content-Type值.