【问题标题】:Knockout AJAX data sent to C# controller is null发送到 C# 控制器的 Knockout AJAX 数据为空
【发布时间】:2014-07-31 17:08:06
【问题描述】:

我正在尝试将颜色列表(id 编号)发布到我的控制器中的测试功能。我知道数据正在发送并且看起来格式正确。

当我发送数据时 fiddler 显示:

[{"ID":"15","Duration":"Permanent","bNotPermanent":"1"},   
{"ID":"21","Duration":"Permanent","bNotPermanent":"1"}]

淘汰 AJAX 帖子:

        SendData = ko.toJSON(self.AddColors) ;
        alert(SendData);

        $.ajax({
            ContentType: 'application/json; charset=utf-8',
            dataType: "json",
            type: "POST",
            url: '/EditColor/PostColors',
            data: SendData
        }).success(function (data) {

        });

我正在使用的数据类:

public class AjaxColorList
{
    public string ID { get; set; }
    public string Duration { get; set; }
    public string bNotPermanent { get; set; }
}

控制器功能: (我还尝试了 public JsonResult PostColors(String AddColors 只是为了看看是否有任何结果)

    public JsonResult PostColors(List<Helpers.AjaxColorList> AddColors)
    {
        var ColorList = AddColors;  // breakpoint set here
        ....
    }

在上面函数的断点处,我看到 AddColors 为空。我确保 JSON 查询中的字段与数据类中的字段匹配。我错过了什么?

我还更改了代码,使其仅将一个对象传递给控制器​​,以验证它是否可以接收某些东西……任何东西。

添加的控制器函数如下所示:

    public JsonResult RequestAddColor(Helpers.AjaxColor AddColor)
    {
        var color = AddColor; // breakpoint here


         ...
    }

提琴手显示:

{"ID":"11","Duration":"Permanent","bNotPermanent":"false"}

但控制器将所有变量显示为空。

这一定是我想念的愚蠢/简单的东西。任何人都可以看到我的逻辑中的错误吗?

【问题讨论】:

    标签: c# asp.net-mvc-4 knockout.js asp.net-ajax


    【解决方案1】:

    为您的 ajax 调用尝试这种格式,我重新创建了场景,这对我有用:

              $.ajax({
                    url: '/Home/PostColors',
                    contentType: "application/json",
                    async: true,
                    type: "POST",
                    data: JSON.stringify(sendData),
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log("FAIL: " + errorThrown);
                    },
                    success: function (data, textStatus, jqXHR) {
                        console.log("SUCCES");
                    }
                });
    

    【讨论】:

    • 嗯。如果我这样做,它希望我添加 system.http.web;与 system.mvc.web; 冲突。如果我注释掉 system.mvc.web 以与 system.http.web 一起使用,我会列出各种编译器错误,因为控制器、视图结果等......不再定义......
    • 这可能是针对 WebAPI 控制器的,这篇文章建议在方法名称之前添加 [HttpPost] 属性。 vault.lozanotek.com/archive/2010/04/16/…
    • 这个例子是将数组数据放入方法期望的参数名称中:forums.asp.net/t/…
    • 这正是我在数组的第一次迭代中所做的,这就是为什么我很困惑为什么当它在提琴手中清楚地显示它正在发送时数据为空。
    • 试试上面更新的 ajax 格式,看看是否适合你。
    猜你喜欢
    • 2021-10-08
    • 2013-05-03
    • 2017-03-11
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2021-02-14
    • 2023-03-26
    • 2023-03-20
    相关资源
    最近更新 更多