无法将具有键值对数组的JavaScript对象发布到Web Api

时间:2015-02-25 21:35:18

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

我有一个对象(下面的模型)我用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
}

1 个答案:

答案 0 :(得分: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您可以看到仅限于键和值的属性有吸气剂