[英]ASP.NET Web API Sending Complex Objects to Frontend
I've been trying to search in both Google and here if there was a question similar to mine but most of the questions involved the opposite of what I want to happen. 我一直在尝试在Google和此处进行搜索,是否存在与我类似的问题,但是大多数问题都与我想发生的事情相反。
So I have an object like this: 所以我有一个这样的对象:
class MyObject
{
int SomeID {get; set;}
string SomeName {get; set;}
List<AnotherObjectContainingIDAndString> {get; set;}
}
So after creating my controller and filling up my object, I tried sending it over and when I checked through Postman I get all the properties except for the List one. 因此,在创建控制器并填满对象之后,我尝试将其发送过来,当我通过邮递员检查时,我得到了除列表一以外的所有属性。 My question is if this is even possible or if I'm not able to send an array within an object?
我的问题是这是否有可能或者我是否无法在对象内发送数组?
Here's how my controller looks like for a bit of context: 以下是我的控制器的外观:
[HttpGet("{id}"]
public async Task<ActionResult<MyObj>> GetById(int id)
{
var myObj = await _context.MyObjs.Where(t => t.Id == id).SingleOrDefaultAsync();
if (myObj == null)
{
return NotFound();
}
List<ObjectDescribedInPreviousCodeBlock> myList = new List<ObjectDescribedInPreviousCodeBlock>();
//Fill the list up
var toSendOver = new MyObject();
//Assign the properties to toSendOver
return toSendOver;
}
Try decorating your classes to serialize with these: 尝试装饰您的类以使用以下方法进行序列化:
[DataContract]
class MyObject
{
[DataMember]
int SomeID { get; set;}
[DataMember]
string SomeName { get; set;}
[DataMember]
List<AnotherObjectContainingIDAndString> { get; set;}
}
You can normally pass your model to the view but first you must initialize your list variable. 您通常可以将模型传递给视图,但首先必须初始化列表变量。
class MyObject { public MyObject() { ListAnotherObjectContainingIDAndString = new List<AnotherObjectContainingIDAndString>(); } int SomeID { get; set; } string SomeName { get; set; } List<AnotherObjectContainingIDAndString> ListAnotherObjectContainingIDAndString { get; set; } }
There's no way this compiles(you must not be showing actual code, so you might have some other simple error we could identify if you posted actual code) 无法编译(您必须不显示实际代码,因此,如果发布了实际代码,您可能会遇到一些其他简单的错误,我们可以确定)
List<AnotherObjectContainingIDAndString> {get; set;}
It's missing a property name such as 它缺少属性名称,例如
List<AnotherObjectContainingIDAndString> ListOfItems {get; set;}
Additionally you'd need to assign the list you created to the object: 另外,您需要将创建的列表分配给该对象:
toSendOver.ListOfItems = myList;
Lastly you're returning a MyObject
which is different type from your action signature which indicates the return is a ViewLessonVM
. 最后,您返回的
MyObject
与操作签名的类型不同,这表明返回的是ViewLessonVM
。 Although sometimes the framework will map properties, I don't think this will work on returns. 尽管有时框架会映射属性,但我认为这不会对返回值起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.