【问题标题】:Problems binding a radio button group in Razor Pages在 Razor Pages 中绑定单选按钮组时出现问题
【发布时间】:2020-02-17 15:37:10
【问题描述】:

我在 ASP.NET Core 3.0 Razor 页面中使用单选按钮组时遇到了一些问题。本质上,我想使用单选组而不是选择,但我不知道如何将它正确绑定到我的 InputModel。

Code 用于相关的 Razor 页面。当然,还有 repo 中的其余代码。

在我的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.

写入控制台。

【问题讨论】:

  • 您可能需要 [Bindproperty] 标记,除非您在粘贴的代码之外有 [BindProperties]。可能会令人困惑的是模型属性的名称与类完全相同。而不是Rating Rating,使用Rating FormRating 可能是有益的。祝你好运!

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-03-31
    • 2011-10-17
    • 2020-05-26
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 2019-06-08
    • 1970-01-01
    相关资源
    最近更新 更多