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 type="submit" value="Buy" asp-page-handler="Buy" />
<input 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) });
}
}
CodePudding user response:
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>