I am using Razor Pages. I have two fields that in a model that are NOT required:
`    public class OrderModel : EntityModel, IValidatableObject
    {        
        public string UserId { get; set; } 
        public int PortfolioId { get; set; }
        public int StockId { get; set; }
        public int StockHoldingId { get; set; }
        public string StockSymbol { get; set; } 
        [Required]
        [DisplayName("Shares Traded")]
        public int QuantityTraded { get; set; }`
The two fields are UserId and StockSymbol. I have the following portion of a form, with the UserId and StockSymbol being nonexistent so null or empty, which I am purposely doing:
`        <div>
            Quantity: <input type="number" min="0" asp-for="@Model.Order.QuantityTraded" />
            <input type="hidden" asp-for="@Model.Stock.Id" />
            <input type="hidden" asp-for="@Model.Stock.Symbol" />
            <input type="hidden" asp-for="@Model.Stock.Price" />
            <input type="hidden" asp-for="@Model.Stock.StockName" />
            <input type="hidden" asp-for="@Model.Stock.Description" />
            <input class="btn-primary" type="submit" value="Buy" asp-page-handler="Buy" />
            <input class="btn-primary" type="submit" value="Sell" asp-page-handler="Sell" />
        </div>`
When I submit the form, I am having an invalid ModelState as shown below:

It is showing "UserId field is required" and "StockSymbol field is required". What else can be causing this requirement, when the [Required] attribute is clearly not there for them?
As requested, Here is the Validate method:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (QuantityTraded < 1)
    {
        yield return new ValidationResult(
            $"Quantity must be greater than 0.",
            new[] { nameof(QuantityTraded) });
    }
}
Do this. may be following things will help you. Its applicable for updated .NET core 5 > versions.
public class OrderModel
{        
    public string? UserId { get; set; }
    public string? StockSymbol { get; set; }
}
Or remove following tag in .csproj file
<Nullable>enable</Nullable>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With