即使从选择标记中选择项目,验证消息仍会显示

Validation message still appear even after select an item from select tag

提问人:Abdulsalam Elsharif 提问时间:8/11/2022 最后编辑:Abdulsalam Elsharif 更新时间:8/11/2022 访问量:440

问:

我使用不显眼的验证来验证客户端的表单,如果我单击提交按钮,则会出现验证消息,如果我开始在输入字段中输入验证消息,则验证消息消失了,选择标签会出现问题,如果我从列表中选择一个项目,则仍然显示验证消息。

这是班级Business

public class Business
{
    [Key]
    public int Id { get; set; }
    
    [Required]
    public string? Name { get; set; }

    [Required(ErrorMessage = "Please select business type")]
    public int? BusinessTypeId { get; set; }

    public BusinessType? BusinessType { get; set; }
    
}

BusinessType

public class BusinessType
{
    public int Id { get; set; }

    [Required]
    public string? Name { get; set; }


    public ICollection<Business>? Businesses { get; set; }
}

和标签select

 <select class="form-select" asp-for="BusinessTypeId" asp-items="@(ViewData["BusinessTypeList"] as SelectList)" data-control="select2" data-hide-search="true" data-placeholder="Select a Business type">
   <option value="">Select Business Type</option></select>
 <span asp-validation-for="BusinessTypeId" class="text-danger"></span>
jQuery ASP.NET-CORE 验证 unobtrusive-validation

评论

0赞 kyenry 8/11/2022
首先,尝试将属性添加到您的[Required]BusinessType
0赞 Abdulsalam Elsharif 8/11/2022
@VeronicaAsuquo没有任何变化,同样的问题仍然存在
0赞 kyenry 8/11/2022
我将发布一个可以用于 selectlist 的帮助程序方法的示例

答:

0赞 kyenry 8/11/2022 #1

试试这个

public static class SelectListHelper
{
    public static async Task<List<SelectListItem>> BusinessTypes(this ApplicationDbContext dbContext, int? selected = null)
    {
        var data = await dbContext.BusinessTypes.Select(s => new SelectListItem
        {
            Text = s.Name,
            Value = s.Id.ToString(),
            Selected = s.Id == selected
        }).ToListAsync();

        return data.prepend(new SelectListItem(){ Text = "Select a Business type", Value = null });
    }
}

您的商务舱航班

 public class Business
 {
    [Key]
    public int Id { get; set; }

    [Required]
    public string? Name { get; set; }

    [Required(ErrorMessage = "Please select business type")]
    public int? BusinessTypeId { get; set; }
 }

然后是你的观点

@model Business
@inject ApplicationDbContext context;

<select class="form-select" asp-for="BusinessTypeId" asp-items="SelectListHelper.BusinessTypes(context, BusinessTypeId)" data-control="select2" data-hide-search="true"></select>
<span asp-validation-for="BusinessTypeId" class="text-danger"></span>
0赞 Abdul Haseeb 8/11/2022 #2

尝试获取下拉列表。Html.DropDownListFor

Inside Controller Action Method

Viewbag.BusinessTypeList = new SelectList(dbcontext.BusinessType.ToList(),"Id","Name");

Inside View

@Html.DropDownListFor(model => model.BusinessTypeId, ViewBag.BusinessTypeList as SelectList, 
     "-- Select Business Type ---",new { @class = "form-control" })

添加以下内容jquery scripts

jquery.validate.js and jquery.validate.unobtrusive.js