Home > Back-end >  Validation message still appear even after select an item from select tag
Validation message still appear even after select an item from select tag

Time:08-12

I used unobtrusive validation to validate the form in client side, If I click on submit button the validation messages appear, If I start typing in input field the validation message disappeared, The problem happen with select tag, If I select an item from the list, the validation message still appears.

Here is the Business class

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 class

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

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


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

And the select tag

 <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" ></span>

CodePudding user response:

Try this

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 });
    }
}

Your Business Class

 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; }
 }

Then your view

@model Business
@inject ApplicationDbContext context;

<select  asp-for="BusinessTypeId" asp-items="SelectListHelper.BusinessTypes(context, BusinessTypeId)" data-control="select2" data-hide-search="true"></select>
<span asp-validation-for="BusinessTypeId" ></span>

CodePudding user response:

Try Html.DropDownListFor to get 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" })

Add the following jquery scripts

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

  • Related