在Razor页面中绑定单选按钮组时出现问题

时间:2019-10-21 14:11:53

标签: asp.net asp.net-core razor .net-core razor-pages

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.

写出到控制台。

1 个答案:

答案 0 :(得分:0)

int Rating中使用Rating Rating代替完整的InputModel似乎已经解决了这个问题。