Search code examples
asp.net-core.net-corerazor-pages

Why is the object not selected?


I wrote this code-


         ViewData ["ProductId"] = new SelectList (_context.Set <Product> (), "Id", "ProductsTitle", _context.Product.Where (m => m.Id == productId) .FirstOrDefault ());

But the selected object (_context.Product.Where (m => m.Id == productId) .FirstOrDefault ()) is not selected on the page.

How can I fix the code to make it work?

Regards


Solution

  • If you want to select a specific object, you only need to pass in the id.

     ViewData ["ProductId"] = new SelectList (_context.Set <Product> (), "Id", "ProductsTitle", productId);
    

    View:

    <select asp-for="ProductId" class="form-control" asp-items="ViewBag.ProductId"></select>