gpt4 book ai didi

asp.net-core - 表单字段是必需的,即使未如此定义

转载 作者:行者123 更新时间:2023-12-05 01:04:24 24 4
gpt4 key购买 nike

我正在使用带有 Fluent Validation 的 Net 6,并且我有一个带有以下字段的表单:

  <form method="post" asp-controller="Product" asp-action="Create" asp-antiforgery="true" autocomplete="off">
<label asp-for="Description">Description</label>
<input asp-for="Description" type="text">
<span asp-validation-for="Description" class="error"></span>
...
<button class="submit" name="button">Create</button>
</form>

ProductModel是:

public class ProductModel {

public String Description { get; set; }

// ...
}

ProductModel Fluent Validator 是:

公共(public)类 ModelValidator : AbstractValidator {

public ModelValidator() {

RuleFor(x => x.Description)
.Length(0, 200).WithMessage("Do not exceed 200 characters");

// ...

}

}

当我提交表单时,如果我让它为空,我会收到描述错误:

The Description field is required.

但我的验证器不需要描述。

这发生在所有领域。未填写时,我会收到类似的错误。

我错过了什么?

最佳答案

做了一点挖掘,这似乎是由于与模型验证更改有关的问题;特别是在 ASP Net 6 中。我找到了一个可以比我更好地解释它的文档链接,但我也会给出一个代码实现:Microsoft docs

builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

//Removes the required attribute for non-nullable reference types.

希望这会有所帮助,我直接从 MS 文档中获取了此代码,所以如果它不能解决您的问题,可能还有其他原因。

关于asp.net-core - 表单字段是必需的,即使未如此定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72060349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com