c# - 如何将返回的 ajax 数据作为 C# 对象列表传递给 Controller ​​?

标签 c# javascript jquery asp.net-mvc-4

我编写了一个 ajax 函数,它将从 Controller 接收 json 结果。现在,我希望在每次调用中将返回的数据传递给 Controller ​​并将其转换为 C# 对象。

我正在使用jquery1.7,我尝试了这个:

$("document").ready(function () {
    var returningData="";
    $("select").change(function () {
        $.getJSON("/product/GetProductDetailsByValue", { amount: $(this).val(),returningProductDetails:returningData }, function (data) {
        returningData = data.serialize();
        });
    });
});

在 Controller 中我有这个:

[HttpGet]
public JsonResult GetProductDetailsByValue(string amount, string returningProductDetails)
{
    List<ProductDetail> obj = (new JavaScriptSerializer()).Deserialize<List<ProductDetail>>(returningProductDetails);
...
}

但是returningProductDetails始终为空。

我尝试直接发送数据而不对其进行序列化,并且在 Controller 中我尝试接收 List<ProductDetail>但我在 Controller 中收到一个列表,其中包含一些对象,但它们的所有字段均为空。

如何做到这一点?

更新

当我直接发送数据而不进行序列化时,我将收到一些带有空字段的对象,但在浏览器的控制台中我可以看到参数包含一个金额和一些 ProductDetails并且产品详细信息根本不为空,而当我在 Controller 中设置断点时,我看到一些空的产品详细信息。我认为在 Controller 中我没有等待正确的数据类型。

最佳答案

尝试将 javascript 中的返回项目详细信息更改为此

 $("select").change(function () {
$.ajax({
                    type: "GET",
                    url: "/product/GetProductDetailsByValue",
                    data: { amount: $(this).val(), returningProductDetails: returningData },
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                    returningData = data;

                    }
                });

});)

并在您的 Controller 中使用它(就像以前一样)

List<ProductDetail> returningProductDetails

关于c# - 如何将返回的 ajax 数据作为 C# 对象列表传递给 Controller ​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950775/

相关文章:

c# - 获取两个列表之间的差异

c# - 带有触摸动画的 TableView 展开和折叠部分

javascript - 使用 JavaScript 替换字符串中的 '/'

JavaScript。引用动态创建的变量

C# AC 电源连接/断开事件

javascript - 比较来自 JSON 的信息,返回列表中的顶部结果

javascript - 控制台.log();如何调试javascript

javascript - 尝试在 jQuery 中找到更好的方法

javascript - 在动态创建的输入上实例化日期选择器

c# - XMLSerializer 为什么要取基类的 DefaultValue 属性来序列化