Ras
Ras

Reputation: 43

How do I display and assign foreign keys on an object in MVC Core?

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

Answers (1)

atiyar
atiyar

Reputation: 8305

  1. add a World property to your Kingdom class so that Kingdom becomes -
public class Kingdom
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? WorldId { get; set; }

    public World World { get; set; }
}
  1. right click on your Controllers folder, then select "Add", then select "Controller"
  2. then from the dialog box select "MVC controller with views, using Entity Framework"
  3. select Kingdom from Model class dropdown, and also select your DbContext
  4. click Add

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

Related Questions