Dataset null reference exception

Eddy Wu 20 Reputation points
2023-06-02T02:57:02.94+00:00

I have a very simple page that retrieves records from the database and displays them on the page. In the code behind page, the records are retrieved successfully, but in the index.cshtml, it is raising a null reference exception error. Any idea why?

WeChat Image_20230602105332

WeChat Image_20230602105343

WeChat Image_20230602105339

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,360 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,076 Reputation points Microsoft Vendor
    2023-06-02T05:45:58.3066667+00:00

    Hi @Eddy Wu

    User's image

    The null reference exception relates the above code, in the OnGet method, you create a new DataSet instance and set the data for it, without setting the data for the MenuItems property of PageModel. So, in the view page, it will show the null reference exception.

    To solve this issue, change your code as below:

        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
               
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
            public DataSet MenuItems { get; set; }
            public void OnGet()
            {
                  ... // in the using statement.
                   MenuItems = new DataSet();
                   sda.Fill(MenuItems);
                  ...
            }
        }
    

    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

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful