The model in the parameter has values all the way to the DAL method where the query is but somehow nothing changes in the database. Anyone got any clue why? Also no errors occurred.
Controller:
public ActionResult AddCar(CarModel car)
{
if(ModelState.IsValid)
{
u.AddCar(new DTO.CarDTO(car.Color, car.Type, car.NumberOfSeats, car.Price, car.MaxKilometres, car.Addition, car.ModelID, car.License_Plate, car.Fueltype, car.ReservationStatus));
return RedirectToAction("Index", "Home");
}
return View();
}
Logic:
public void AddCar(CarDTO c)
{
carDAL.AddCar(new CarDTO(c.Color, c.Type, c.NumberOfSeats, c.Price, c.MaxKilometres, c.Addition, c.ModelID, c.License_Plate, c.Fueltype, c.ReservationStatus));
}
Interface layer:
public interface ICarDAL<CarDTO>
{
public void AddCar(CarDTO c) { }
}
DAL, class does have connectionstring:
public void AddCar(CarDTO c)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "INSERT INTO [dbo].[Car](Price, Addition, License_Plate, MaxKm, Type, Color, NumberOfSeats, Fueltype, reservationStatus, ModelID) " +
"VALUES(@Price, @Addition, '@LicensePlate', @MaxKm, '@Type', '@Color', @NumberOfSeats, @FuelType, @Reserved, @ModelID)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@Price", c.Price);
cmd.Parameters.AddWithValue("@Addition", c.Addition);
cmd.Parameters.AddWithValue("@LicensePlate", c.License_Plate);
cmd.Parameters.AddWithValue("@MaxKm", c.MaxKilometres);
cmd.Parameters.AddWithValue("@Type", c.Type);
cmd.Parameters.AddWithValue("@Color", c.Color);
cmd.Parameters.AddWithValue("@NumberOfSeats", c.NumberOfSeats);
cmd.Parameters.AddWithValue("@FuelType", c.Fueltype);
cmd.Parameters.AddWithValue("@ReservationStatus", c.ReservationStatus);
cmd.Parameters.AddWithValue("@ModelID", c.ModelID);
}
}
}
Found the error but I still dont know how to fix it: https://i.sstatic.net/Stdh5.jpg
Solution: First of all I needed to use ExecuteNonQuery() to make the query actually do something...I thought SqlCommand already executed it for you. Secondly my password consisted out of ************ which I thought it wouldn't matter but I guess it did.
cmd.ExecuteNonQuery();after assigning your params would work. Also on another note useAddand specify the data type notAddWithValueas the values would be inferred and may not be what you need.cmd.Parameters.AddWithValue();. But now I get 'ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.'ExecuteNonQuery(). Also the problem was that my password consisted of only ********* instead of the actual password, but thanks for helping :D