在 ASP.NET Core 3.0剃须刀页面上使用单选按钮组时,我有些麻烦。本质上,我想使用单选组而不是选择组,但我不知道如何将其正确绑定到我的InputModel。
Code表示有问题的剃刀页面。当然,还有回购中的其余代码。
在我的cshtml.cs
中,我有一个这样定义的输入模型
public class InputModel
{
[Required]
[StringLength(
CTConfig.Story.MaxTitleLength,
ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.",
MinimumLength = CTConfig.Story.MinTitleLength
)]
public string Title { get; set; }
[Required]
[StringLength(
CTConfig.Story.MaxDescriptionLength,
ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.",
MinimumLength = CTConfig.Story.MinDescriptionLength
)]
public string Description { get; set; }
[Required]
[StringLength(
CTConfig.Story.MaxHookLength,
ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.",
MinimumLength = CTConfig.Story.MinHookLength
)]
public string Hook { get; set; }
[DataType(DataType.Upload)]
[MaxFileSize(CTConfig.Story.CoverMaxWeight)]
[AllowedExtensions(new[] {".jpg", ".jpeg", ".png"})]
public IFormFile Cover { get; set; }
[Required]
public Rating Rating { get; set; }
[Required]
public List<Tag> Tags { get; set; }
}
,.cshtml
文件中的单选按钮组如下所示:
<div class="form-group">
<label>Rating</label>
<p>The age rating</p>
@foreach (var rating in Model.Ratings)
{
<div class="form-check">
<input asp-for="Input.Rating" class="form-check-input" type="radio" id="@rating.Name.ToLower()" value="@rating.Id" checked>
<label class="form-check-label" for="@rating.Name.ToLower()">@rating.Name</label>
</div>
}
<span asp-validation-for="Input.Rating" class="text-warning"></span>
</div>
,并且请求在发送表单时也显示为correct。
但是如果我写出错误
foreach (var msv in ModelState.Values)
{
foreach (var error in msv.Errors)
{
Console.WriteLine(error.ErrorMessage);
}
}
我得到了错误
The Rating field is required.
写出到控制台。
答案 0 :(得分:0)
在int Rating
中使用Rating Rating
代替完整的InputModel
似乎已经解决了这个问题。