2015-04-02 67 views
0

我正在对我的web API进行ajax POST调用并发布JSON。下面是我的代码在Web API中获取复杂对象的问题发布

C#类:

public class Employee:EmployeeBase 
{ 
    private string _EId; 
    private string _EName; 
    private string _Designation; 
    private EmployeeBase[] _Expirence; 

    public string EId 
    { 
     get { return _EId; } 
     set { _EId = value; } 
    } 
    public string EName 
    { 
     get { return _EName; } 
     set { _EName = value; } 
    } 
    public string Designation 
    { 
     get { return _Designation; } 
     set { _Designation = value; } 
    } 
    public Expirence[] MyExpirence 
    { 
     get { return _Expirence; } 
     set { _Expirence = value; } 
    } 
} 

public class EmployeeBase 
{ 
    private string _Id; 
    private string _Company; 
    private string _Years; 

    public string Id 
    { 
     get { return _Id; } 
     set { _Id = value; } 
    } 
    public string Company 
    { 
     get { return _Company; } 
     set { _Company = value; } 
    } 
    public string Years 
    { 
     get { return _Years; } 
     set { _Years = value; } 
    } 
} 

控制器:

[HttpPost] 
public ActionResult SaveAssociatDisassociateCameras(Employee zone) 
{ 
} 

样品JSON:

示例1:

{ 
    "Id":"E100", 
    "Name":"TestEmployee", 
    "Designation":"Test Engineer", 
    "MyExpirence":[ 
     { 
     "Id":"01", 
     "Company":"Company1", 
     "Years":"10" 
     } 
    ] 
} 

示例2:

{ 
    "Id":"E100", 
    "Name":"TestEmployee", 
    "Designation":"Test Engineer", 
    "MyExpirence":[ 
     { 
     "Id":"01", 
     "Company":"Company1", 
     "Years":"10" 
     } 
    ], 
    "DummyArray":[ 

    ] 
} 

现在的问题是,当我张贴样品1 JSON是越来越正确地发布到控制器。但是在控制器MyExpirence数组中是null。但是我得到了EId,EName等的值。只有MyExpirence数组为null。

另一方面,如果我发布示例2添加一个虚拟数组到JSON我得到正确的值。在这种情况下,我为EId,EName甚至MyExpirence数组获得了合适的值。

我不明白为什么我会在样本1中为MyExpirence变为空。而且我对样本2解决方案并不满意。我想要一个正确的方法来做到这一点。

+2

没有答案的,但是'Expirence'拼写'Experience' – Tom 2015-04-02 12:45:15

+0

你为什么要获得从''EmployeeBase' Employee'? – 2015-04-02 12:55:01

+0

发布此课程的教程:Expirence,MyExpirence中使用的[] – 2015-04-02 12:56:39

回答

0

您的代码无法编译:_ExpirenceMyExpirence属性不同。修复它像下一个样品

public class Employee:EmployeeBase 
{ 
    private string _EId; 
    private string _EName; 
    private string _Designation; 
    private EmployeeBase[] _Expirence; 

    public string EId 
    { 
     get { return _EId; } 
     set { _EId = value; } 
    } 
    public string EName 
    { 
     get { return _EName; } 
     set { _EName = value; } 
    } 
    public string Designation 
    { 
     get { return _Designation; } 
     set { _Designation = value; } 
    } 
    public Expirence[] MyExpirence 
    { 
     get { return _Expirence; } 
     set { _Expirence = value; } 
    } 
}