[英]ModelState showing validationstate as invalid for a field that is not required
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.这两个字段是 UserId 和 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:
我有一个表单的以下部分,其中 UserId 和 StockSymbol 不存在,因此为空或为空,这是我故意做的:
` <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:当我提交表单时,我有一个无效的 ModelState,如下所示:
It is showing "UserId field is required" and "StockSymbol field is required".它显示“需要 UserId 字段”和“需要 StockSymbol 字段”。 What else can be causing this requirement, when the [Required] attribute is clearly not there for them?
当 [Required] 属性显然不适合他们时,还有什么可能导致此要求?
As requested, Here is the Validate method:根据要求,这是 Validate 方法:
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.
它适用于更新的 .NET core 5 > 版本。
public class OrderModel
{
public string? UserId { get; set; }
public string? StockSymbol { get; set; }
}
Or remove following tag in.csproj file或删除 .csproj 文件中的以下标签
<Nullable>enable</Nullable>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.