我在客户端使用了不引人注目的验证来验证表单,如果我点击提交按钮,验证消息就会出现,如果我开始在输入字段中键入,验证消息就消失了,select标记出现了问题,如果我从列表中选择了一个项目,验证消息仍然会出现。
这是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>
试试这个
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>
尝试Html.DropDownListFor
获取dropdownlist。
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