【问题标题】:Trouble posting a JavaScript object with an array of Key Value Pairs to Web Api将带有键值对数组的 JavaScript 对象发布到 Web Api 时遇到问题
【发布时间】:2015-04-28 02:24:06
【问题描述】:

我有一个对象(下面的模型)我已经用 JavaScript 填充了客户端,我需要将它发布到我的服务器。在我期望接收的类服务器端中定义了相应类型的对象。

当我尝试发布该对象时,除了单个属性外,所有内容都可以正常发布。此属性在服务器端定义为List<KeyValuePair<Guid,Bar>>Bar 似乎不是问题,因为我可以发布它就好了。

在客户端,我尝试以几种方式重新格式化 JavaScript 对象上的相应属性(作为对象对数组,作为对象上的文字属性等),但它始终是一个空列表它到达服务器。

我猜这是一个语法问题,但我无法弄清楚正确的语法是什么,而且我在网上看到了很多相互矛盾的例子。我希望有人可以根据经验谈谈应该如何发布。

//C# Class MockUp
public class Foo
{
    public Guid FooId {get;set;}
    public string Description {get;set;}
    public bool Inactive {get;set;}
    public List<KeyValuePair<Guid,Bar>> FooBar {get;set;} //This comes over as null regardless of how I arrange the object client-side.
}

//TypeScript Class MockUp
class Foo {
    fooId: string;
    description: string;
    inactive: boolean;
    fooBar: Array<KeyValuePair>;
}
class KeyValuePair {
    key: string;
    value: Bar
}
class Bar {
    //...Implementation here mathces Bar on the server
}

【问题讨论】:

  • 尝试将属性类型更改为object 而不是List&lt;KVP&lt;Guid, Bar&gt;&gt;
  • 我不确定我是否理解您的意思。 TypeScript 会自动将其编译成 object 类型...
  • @CallumLinington 阅读下面的 konkked 答案后,我明白了你的意思。那是正确的方法。我很好奇为什么它不会让你发布 KVP。毕竟,它们是一个类(就像交替实现的对象一样)。
  • 类型不能太复杂,否则 C# 模型绑定器不知道如何反序列化它。你可以试试 Json.NET

标签: javascript typescript asp.net-web-api


【解决方案1】:

如果你为 foobar 创建一个 dto 就可以了

public class FooDto
{
    public Guid FooId {get;set;}
    public string Description {get;set;}
    public bool Inactive {get;set;}
    public List<FooBarDto> FooBar {get;set;} 
}

public class FooBarDto
{
    public Guid Key {get;set;}
    public Bar Value {get;set;}
}

KeyValuePair 在这种情况下不起作用的原因是因为KeyValuePair 中的属性是只读的,看看这里 at the msdn docs 你可以看到 Key 和 Value 属性只有 getter

【讨论】:

  • 不需要,C#可以反序列化类型。
  • @CallumLinington 通过重新阅读问题意识到这不是问题
  • @konkked 成功了。不过我很好奇为什么。有什么理由不应该与 KeyValuePair 一起使用?
  • @Locke 更新答案,KeyValuePair 属性上基本没有写,所以不会正确序列化
  • 谢谢,konkked。这是有道理的——我没有考虑到它们是只读的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 2015-03-22
  • 1970-01-01
相关资源
最近更新 更多