Model state returns false everytime I click on submit
create table Orders (
UserId nvarchar(450),
OrderType varchar(50) not null,
DineInDate Date not null,
DineInTime Time not null,
NumberOfPersons int,
DeliveryAddress nvarchar(450),
CardNumber varchar(20),
ExpirationDate varchar(5),
CVV varchar(3),
PaymentIntentId int
);
@page
@model DiningSystem.Pages.CheckoutModel
@{
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="container mt-5">
<h2 class="text-center mb-4">Checkout</h2>
<form method="post">
<div class="form-group">
<label for="dineInOrDelivery">Choose your option:</label>
<select class="form-control" id="dineInOrDelivery" asp-for="CheckoutOption">
<option value="DineIn">Dine In</option>
<option value="Delivery">Delivery</option>
</select>
<span class="text-danger" asp-validation-for="CheckoutOption"></span>
</div>
<div id="dineInOptions" class="d-none">
<h4>Dine In Details</h4>
<div class="form-group">
<label asp-for="DineInDate">Date</label>
<input type="date" class="form-control" asp-for="DineInDate" min="@DateTime.Today.ToString("yyyy-MM-dd")" />
<span class="text-danger" asp-validation-for="DineInDate"></span>
</div>
<div class="form-group">
<label asp-for="DineInTime">Time</label>
<input type="time" class="form-control" asp-for="DineInTime" />
<span class="text-danger" asp-validation-for="DineInTime"></span>
</div>
<div class="form-group">
<label asp-for="NumberOfPersons">Number of Persons</label>
<input type="number" class="form-control" asp-for="NumberOfPersons" min="1" />
<span class="text-danger" asp-validation-for="NumberOfPersons"></span>
</div>
</div>
<div id="deliveryOptions" class="d-none">
<h4>Delivery Details</h4>
<div class="form-group">
<label asp-for="DeliveryAddress">Address</label>
<input type="text" class="form-control" asp-for="DeliveryAddress" />
<span class="text-danger" asp-validation-for="DeliveryAddress"></span>
</div>
</div>
<h4>Payment Details</h4>
<div class="form-group">
<label asp-for="CardNumber">Card Number</label>
<input type="text" class="form-control" asp-for="CardNumber" />
<span class="text-danger" asp-validation-for="CardNumber"></span>
</div>
<div class="form-group">
<label asp-for="ExpirationDate">Expiration Date</label>
<input type="text" class="form-control" asp-for="ExpirationDate" placeholder="MM/YY" />
<span class="text-danger" asp-validation-for="ExpirationDate"></span>
</div>
<div class="form-group">
<label asp-for="CVV">CVV</label>
<input type="text" class="form-control" asp-for="CVV" />
<span class="text-danger" asp-validation-for="CVV"></span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
<script>
$(document).ready(function () {
$('#dineInOrDelivery').change(function () {
var selectedOption = $(this).val();
if (selectedOption === "DineIn") {
$('#dineInOptions').removeClass('d-none');
$('#deliveryOptions').addClass('d-none');
} else if (selectedOption === "Delivery") {
$('#dineInOptions').addClass('d-none');
$('#deliveryOptions').removeClass('d-none');
} else {
$('#dineInOptions').addClass('d-none');
$('#deliveryOptions').addClass('d-none');
}
}).trigger('change');
});
</script>
using DiningSystem.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Stripe;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Security.Claims;
namespace DiningSystem.Pages
{
public class CheckoutModel : PageModel
{
private readonly IConfiguration _configuration;
private readonly UserManager<ApplicationUser> _userManager;
public CheckoutModel(IConfiguration configuration, UserManager<ApplicationUser> userManager)
{
_configuration = configuration;
_userManager = userManager;
}
[BindProperty]
/*[Required(ErrorMessage = "Please choose an option.")]*/
public string CheckoutOption { get; set; }
[BindProperty]
[DataType(DataType.Date)]
/*[RequiredIf(nameof(CheckoutOption), "DineIn", ErrorMessage = "Please select a date.")]*/
public DateTime? DineInDate { get; set; }
[BindProperty]
[DataType(DataType.Time)]
/*[RequiredIf(nameof(CheckoutOption), "DineIn", ErrorMessage = "Please select a time.")]*/
public TimeSpan? DineInTime { get; set; }
[BindProperty]
[Range(1, int.MaxValue, ErrorMessage = "Please enter a valid number of persons.")]
/*[RequiredIf(nameof(CheckoutOption), "DineIn", ErrorMessage = "Please enter the number of persons.")]*/
public int? NumberOfPersons { get; set; }
[BindProperty]
/*[RequiredIf(nameof(CheckoutOption), "Delivery", ErrorMessage = "Please enter a delivery address.")]*/
public string DeliveryAddress { get; set; }
[BindProperty]
[CreditCard(ErrorMessage = "Please enter a valid card number.")]
/*[Required(ErrorMessage = "Please enter your card number.")]*/
public string CardNumber { get; set; }
[BindProperty]
/*[Required(ErrorMessage = "Please enter the expiration date.")]*/
[RegularExpression(@"^(0[1-9]|1[0-2])\/?([0-9]{2})$", ErrorMessage = "Please enter a valid expiration date (MM/YY).")]
public string ExpirationDate { get; set; }
[BindProperty]
/*[Required(ErrorMessage = "Please enter the CVV.")]*/
[RegularExpression(@"^[0-9]{3,4}$", ErrorMessage = "Please enter a valid CVV.")]
public string CVV { get; set; }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
foreach (var error in errors)
{
Debug.WriteLine(error);
}
return Page();
}
// Get the user ID
string userId = _userManager.GetUserId(User);
// Process the order
string connectionString = _configuration.GetConnectionString("DefaultConnection");
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = @"
INSERT INTO Orders (UserId, OrderType, DineInDate, DineInTime, NumberOfPersons, DeliveryAddress, CardNumber, ExpirationDate, CVV)
VALUES (@UserId, @OrderType, @DineInDate, @DineInTime, @NumberOfPersons, @DeliveryAddress, @CardNumber, @ExpirationDate, @CVV)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@UserId", userId);
command.Parameters.AddWithValue("@OrderType", CheckoutOption);
command.Parameters.AddWithValue("@DineInDate", (object)DineInDate ?? DBNull.Value);
command.Parameters.AddWithValue("@DineInTime", (object)DineInTime ?? DBNull.Value);
command.Parameters.AddWithValue("@NumberOfPersons", (object)NumberOfPersons ?? DBNull.Value);
command.Parameters.AddWithValue("@DeliveryAddress", (object)DeliveryAddress ?? DBNull.Value);
command.Parameters.AddWithValue("@CardNumber", CardNumber);
command.Parameters.AddWithValue("@ExpirationDate", ExpirationDate);
command.Parameters.AddWithValue("@CVV", CVV);
command.ExecuteNonQuery();
}
}
// Redirect to a confirmation page or display a success message
return RedirectToPage("/OrderConfirmation");
}
public void OnGet()
{
}
}
public class RequiredIfAttribute : ValidationAttribute
{
private readonly string _propertyName;
private readonly string _desiredValue;
public RequiredIfAttribute(string propertyName, string desiredValue)
{
_propertyName = propertyName;
_desiredValue = desiredValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_propertyName);
if (property == null)
return new ValidationResult($"Unknown property: {_propertyName}");
var propertyValue = property.GetValue(validationContext.ObjectInstance)?.ToString();
if (propertyValue == _desiredValue && (value == null || string.IsNullOrEmpty(value.ToString())))
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
}