C
C#2y ago
Dasic

❔ How can I pass model data to my controller if I have another POCO class in the model?

Let's imagine that I have the classes:
public class Address
{
public int Id { get; set; }
public string? Street { get; set; }
public string? BuildingNumber { get; set; }
public string? Description { get; set; }
public Entrance[]? Entrances { get; set; }
public DateTime LastEdit { get; set; }
}

public class Entrance
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public Floor[]? Floors { get; set; }
}

public class Floor
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
}
public class Address
{
public int Id { get; set; }
public string? Street { get; set; }
public string? BuildingNumber { get; set; }
public string? Description { get; set; }
public Entrance[]? Entrances { get; set; }
public DateTime LastEdit { get; set; }
}

public class Entrance
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public Floor[]? Floors { get; set; }
}

public class Floor
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
}
How can I create a simple editor for these classes? I mean that my Create() method takes something like this:
public async Task<IActionResult> Create([Bind("Id,Street,BuildingNumber,Description,Entrances")] Address address) { ... }
public async Task<IActionResult> Create([Bind("Id,Street,BuildingNumber,Description,Entrances")] Address address) { ... }
Of course I cannot bind Entrances property because it is another class and it is an array. How can I do the trick? What should my controller accept and how can I do it in the view?
9 Replies
Pobiega
Pobiega2y ago
Is this Blazor or something special? Because in a normal web api, you just do this without any bind attribute at all and it works exactly as expected, assuming you are taking json in
Dasic
DasicOP2y ago
No, it's ASP.NET Core 7
Pobiega
Pobiega2y ago
ok then its literally just
public async Task<IActionResult> Create(Address address) { ... }
public async Task<IActionResult> Create(Address address) { ... }
Pobiega
Pobiega2y ago
ah, this wont be as simple as this isnt for a json webapi - this is for html forms
Dasic
DasicOP2y ago
Thank you. You've also mentioned a json WebAPI, is it the right tutorial to do it? https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-7.0&tabs=visual-studio
Tutorial: Create a web API with ASP.NET Core
Learn how to build a web API with ASP.NET Core.
Pobiega
Pobiega2y ago
sure, that seems okay
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server