【问题标题】:Array post through ajax is null in c# method通过ajax发布的数组在c#方法中为空
【发布时间】:2021-11-28 19:06:12
【问题描述】:

我通过一个循环获取一个数组,并通过一个 ajax 调用将它传递给我的 c# 方法,但由于某种原因,我只在我的参数中获取空值,但数组的计数是通过的。我不确定我做错了什么。例如,在通过 ajax 传递它之前的数组的计数为 3,每个键都填充了所需的信息,但是当我通过 ajax 调用传递它并在 VS 上调试时,我的列表的参数为 null 但有一个计数3 个?

let test = $('.divtest').map(function (index, element) {

    return {
        key1: $(element).closest('.testdiv')[0].id,
        key2: $(element).attr('id'),
        key3: $(element).attr('style')
    }
}).get();

Ajax 调用

$.ajax({
    cache: false,
    type: "POST",
    data: { test: test},
    dataType: "json",
    url: "/controller/testhere",
    success: function (result) {
      alert('done');
    }
});

C#方法

 public JsonResult testhere(List<string> test)
    {
       //stuff
        return null;
    }

【问题讨论】:

  • 试试url: "/controller/testhere?text="+JSON.stringify(test)
  • 呵呵,请问为什么要尝试这种方法? @Vadim

标签: javascript c# arrays json ajax


【解决方案1】:

您的操作是字符串列表,但 ajax 数据不是。试试这个数据

let test = [ "key1", "key2", "key3"];
.....
.ajax({
    cache: false,
    type: "POST",
    data: { test: test},
    dataType: "json",
    url: "/controller/testhere",
    success: function (result) {
      alert('done');
    }
});

否则您将不得不更改操作

创建视图模型

public class TestViewModel
{
public string Key1 {get; set;}
public string Key2 {get; set;}
public string Key3 {get; set;}
}

动作

public JsonResult testhere(TestViewModel test)

【讨论】:

  • 如果我将测试变量更改为那个值,那么我没有捕获我需要的值?那么将我的操作从列表更改为可以接受我需要的操作不是更好吗?
  • @Jack,好的,我更新了答案,再试一次
  • 我确实对我的操作进行了更改,但传入的值仍然为 null
  • 如果您以 json 格式发布您的 javascript 对象,我会很好。
猜你喜欢
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2019-07-17
相关资源
最近更新 更多