Reputation: 43
I have a World object and I have a Kingdom object with a WorldId. I've been trying to find any documentation that will tell me how to, on my create page for my Kingdom object, choose from a list of World objects and based on that bind the FK to the World object's Id.
My world model
public class World
{
public int Id { get; set; }
public string Name { get; set; }
public long Age { get; set; }
}
My Kingdom model
public class Kingdom
{
public int Id { get; set; }
public string Name { get; set; }
public int? WorldId { get; set; }
}
For now, this is my Index Action
public async Task<IActionResult> Index()
{
var model = await _context.Kingdom.ToListAsync();
return View(model);
}
I don't know what methods to use, what are the best practices for achieving this? I have looked at ViewModels, but no good explanations on how to achieve it.
Upvotes: 0
Views: 1431
Reputation: 8305
public class Kingdom
{
public int Id { get; set; }
public string Name { get; set; }
public int? WorldId { get; set; }
public World World { get; set; }
}
This process is called Scaffolding, and it will generate a KingdomsController in your Controller folder and all the views you need in the Kingdoms folder under Views.
Now open the Create.cshtml under Kingdoms in Views. You'll find it has generated a dropdown (html select
) for you to select a World
.
Once you select a World from that dropdown, its Id will be added to your Kingdom model as the foreign key.
Go the Create
action method (the GET one, not the POST one) in your KingdomsController and you'll find where the data for that World select dropdown is coming from.
Run the application, explore the generated code.
You can go through this tutorial for details. Happy coding.
Upvotes: 1