List filled with the same data instead of different data

Viewed 20

I am working on a project in ASP.NET Core (MVC) and have some problem filling a list.

I created a List based on a class, and then using while reader.read() the list is being filled. The problem is that in the end of the while loop the list being filled with the same data instead of different data.

This is the Console output: Console Output

Above the blue line is how the data gets from the sql to the class using the while reader.read() and below is the data after the for loop iterate from the list.

I expect it to be like the above.

HomeController.cs

using Hotels_Parking_Lot_Management.Model;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;

namespace Hotels_Parking_Lot_Management.Controllers
{
    public class HomeController : Controller
    {
        public List<ParkingSpots> parkingSpotsList = new List<ParkingSpots>();
        public IActionResult Index()
        {
            FetchData(new ParkingSpots());
            return View(parkingSpotsList);
        }

        [HttpPost]
        public IActionResult Index(ParkingSpots spot)
        {
            try
            {
                ParkingSpots.value = Convert.ToInt32(Request.Form["value"]);
                Response.Redirect("/NewSpot");
            }
            catch (Exception err) { Console.WriteLine(err); }
            return View();
        }

        private void FetchData(ParkingSpots spot)
        {
            using (var conn = new SqlConnection(db.connString))
            {
                conn.Open();
                var commnad = "SELECT * FROM spots";
                using (var cmd = new SqlCommand(commnad, conn))
                {

                    var reader = cmd.ExecuteReader();
    
                    while (reader.Read())
                    {
                        spot.formValue = Convert.ToInt32(reader["value"].ToString());
                        spot.state = Convert.ToInt32(reader["state"].ToString());
                        Console.WriteLine(spot.formValue + " " + spot.state);
                        parkingSpotsList.Add(spot);
                    }

                    for (var i = 0; i < parkingSpotsList.Count; i++)
                    {
                        Console.WriteLine(parkingSpotsList[i].formValue);
                        Console.WriteLine(parkingSpotsList[i].state);
                    }
                }

                conn.Close();
            }

        }

    }
}

ParkingSpots.cs

namespace Hotels_Parking_Lot_Management.Model
{
    public class ParkingSpots
    {
        public static int value = 0;

        public int formValue { get; set; }
        public int state { get; set; }
        public string fullName { get; set; }
        public string phone { get; set; }
        public string licensePlate { get; set; }

    }
}

0 Answers
Related