skip to Main Content

Im using visual studio with ASP.NET Core web App (.NET 6.0).Im using Microsoft SQL Server Management Studio 19 as database. Currently, i ran a problem where it display the id instead of name in book index.

I have category table in the database and show it in drop box

enter image description here

But when I show product detail in the index, the category become ID of the category

enter image description here

here is my code: https://github.com/thorgia1702/FPTBook

I have tried make the category name become the FK key in the book table in the Migrations file but have not success

2

Answers


  1. I think the issue with this method is that you should include the foreign object. The reason is that ToListAsync() materialises the query, and if you don’t call Include, the category data will not load.

    public async Task<IActionResult> Index()
    {
         return View(await _context.Books.Include(b => b.Category).ToListAsync());
    }
    

    I also found that when you add a new book, you should use the CategoryId instead of Category.

    var category = await _context.BookCategories.FindAsync(model.CategoryId);
    

    enter image description here

    Login or Signup to reply.
  2. I test your project, and I have the idea like below, could you try the below code?

    1. Remove this line from your .csproj file, read this to know more:

    <Nullable>enable</Nullable>

    In BookController:

    1.change the index action to add .Include to use the Include method to specify related data to be included in query results. :

     public async Task<IActionResult> Index()
            {
                return View(await _context.Books.Include(x=>x.Category).ToListAsync());
            }
    

    2.Change the post create action like your create action in CategoryController:

     public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Price,CategoryId")] Book model)
            {
                if (ModelState.IsValid)
                {
                    _context.Add(model);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
                ViewData["CategoryId"] = new SelectList(_context.Set<Category>(), "CategoryId", "Name",model.CategoryId);
                return View(model);
            }
    

    3.result:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search