c# - 使用 json 传递关联数组 : which type to expect in the controller?

标签 c# asp.net-mvc json

在客户端,我有一个关联数组,用于存储“Guid”-“int”对。 我使用 json 将数组传递给服务器:

  $.ajax({
      url: methodUrl,
      type: 'POST',
      async: false,
      data: { values: items },
      dataType: 'json',
      success: function (data) {
          //...
      }
  });

我尝试传递的对象看起来像这样(取自 Chrome 调试器):

  items: Object
  44f871e0-daee-4e1b-94c3-76d633a87634: 1
  698ce237-3e05-4f80-bb0d-de948c39cd96: 1

在 Controller 中我有一个方法

  public ActionResult Method(Dictionary<Guid, int> values)
  {

  } 

但是,属性值仍然为空。在客户端只有一个 Guids 列表,在 Controller 中有一个 List 一切正常。 我怀疑我应该为 Controller 中的值选择另一种类型,而不是字典。 我还尝试在 ajax 请求中添加“traditional: true”,但没有成功。

感谢任何建议!

最佳答案

这是我在使用 POST 命令时所做的:

var data = {
   values: items
}

var obj = $.toJSON(data);

$.ajax({
      url: methodUrl,
      type: 'POST',
      async: false,
      data: obj,
      dataType: 'json',
      success: function (data) {
          //...
      }
  });

这应该正确地发送到您的 Controller ,您不必使用字典对象,您应该将对象从客户端匹配到服务器端。我将使用具有 Guidint 作为属性的自定义对象,并使用它 - .NET 会将两者匹配起来。话虽如此,使用字典是完全合理的,但这是个人喜好。

public CustomObject 
{
    public Guid MyGuid { get; set; }
    public int MyNumber { get; set; }
}

public ActionResult Method(List<CustomObject> values)
{

} 

有多个参数:

items.SecondNumber = yourVariable; 
// In reality, you'd have a loop around your items and set this SecondNumber.

var data = {
    values: items
}

var obj = $.toJSON(data);


public CustomObject 
{
     public Guid MyGuid { get; set; }
     public int MyNumber { get; set; }
     public int SecondNumber { get; set; } // This is why we use CustomObject
}

关于c# - 使用 json 传递关联数组 : which type to expect in the controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949857/

相关文章:

asp.net-mvc - 如果选择了 DropDownList 的定义选项,则禁用 CheckBox

c# - 如何允许访问 MVC 中的方法?

javascript - 从 API 接收 JSON 对象时出错

c# - 如何为运行时类型创建 List<type>?

c# - Unity3d显示状态栏

c# - Visual Studio 2019 C# WCF 测试客户端无法使用 svcutil.exe

c# - 在 Xamarin Forms 中渲染 HTML 并从 HTML 链接打开嵌入的 PDF

c# - .Net Core 5 应用程序是如何组织/结构化的?或者如何将 n 层类库项目添加到 .Net 核心 Asp.Net 解决方案?

java - Struts 2 中的 Json 插件问题

javascript - 在 React Native 中将 JSON 数据传递到下一页