3

我已经查看了网络以找出我的错误是什么。我发现我尝试过的所有建议都没有成功。我在控制器中访问 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");
                        }
                    });

在调试时填充 DataPost。

控制器

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

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

var dataPost = { 'id': 'id', 'val': 'val' };

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

班级

public class ScheduleData
{
    public string id { get; set; }
    public string val { get; set; }
}

控制器

    public ActionResult UpdateJson(ScheduleData data)
    {//Do something}

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

4

1 回答 1

6

传递的格式是json

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

data: { 'id': id, 'val': val }

但是正如文档清楚地解释的那样,这是使用$.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");
    }
});

注意事项:

  • 用于JSON.stringify(dataPost)确保您将 JSON 字符串发送到服务器
  • contentType: 'application/json'因为那是正确的 Content-Type 值。
于 2013-05-23T08:43:29.380 回答