why i can't display the data from database

Mohammed Ali 1 Reputation point
2023-01-07T01:06:43.79+00:00

why i can't display the data from database

my code as below

@默 List

Azure Database for MySQL
Azure Database for MySQL
An Azure managed MySQL database service for app development and deployment.
712 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2023-01-09T02:18:16.847+00:00

    Hi @Mohammed Ali ,

    From your code, it seems that your application is an Asp.net Core MVC application, right?

    For the NullReferenceException error, it means the page model is null, so when you are using foreach statement to loop the data, it will show this error. I suggest you check the code in the Item Controller, make sure you got data from the Database, and return it to the view page.

    You can refer to the following sample code:

    Controller:

    public class ItemController : Controller  
    {  
        private readonly ApplicationDbContext _dbcontext;  
        public ItemController(ApplicationDbContext applicationDbContext) {  
            _dbcontext = applicationDbContext;  
        }  
        public IActionResult Index()  
        {  
            //query database and get items.  
            var items = _dbcontext.Items.ToList();  
            //return items to the Index.cshtml page.  
            return View(items);  
        }  
    }  
    

    Besides, in the Index.cshtml page, you can also use an If-else statement to check whether the page model is null, then display the result, code like this:

    277200-image.png

    The result as below:
    277198-image1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments