ASP.NET Core Web App - Looping through a DataTable

Chris Undritz 41 Reputation points
2022-12-06T16:43:50.16+00:00

Hello All,

I am creating an ASP.NET Core Web App using C# using .NET6.0. I have only just started and looking to complete a connection to an existing SQL database and just quickly display some data to prove the connection and the SQL Queries.

This is my setup; I have only created one page so far: ‘dashboard.cshtml’
267872-dashboardcshtmlcs-overview.png

267856-dashboardcshtml-overview.png

The SQL query works fine and, when stepping through the code, returns the expected values from the database as you can see below:
267881-dashboardcshtmlcs-datatable-value.png

I also added a string variable to see if this would display and also to test the display of a single variable in the front end. As you can see the expected value is assigned
267846-dashboardcshtmlcs-messsage-value.png

However, as you can see from the images above, there is a problem with the reference to the variables ‘message’ and ‘dtsensors’ in the html and so the application does not run. The errors are below:
267882-errors.png

So, could anyone help me to understand what the error message ‘the name <variable> does not exist in the current context’? And how to fix it? Also, could some one confirm how I loop through a DataTable in the front end? I cannot find any documentation on this.

Thanks in advance

Developer technologies ASP.NET ASP.NET Core
SQL Server Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-12-07T06:09:12.693+00:00

    Hi @Chris Undritz ,

    268082-image.png

    Razor exposes a Model property for accessing the model passed to the view, so you can access the properties via the @Model.{PropertyName}, refer to the following screenshot:

    267985-image.png

    More detail information about Razor syntax, see Razor syntax reference for ASP.NET Core.


    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

5 additional answers

Sort by: Most helpful
  1. Chris Undritz 41 Reputation points
    2022-12-07T12:11:55.567+00:00

    So I have managed to put in place a solution. I loop through the datatable in the C# code to create a sensor class data object and I am able to loop through that in the front end. Management seem happy enough with this so result!


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.