SelectList Data Annotation claimed as empty or not selected?

Dondon510 261 Reputation points
2025-04-10T09:26:59.8766667+00:00

Hi All, I don't understand why my SelectList Data Annotation claimed as empty or not selected?

**my.cls**
public class Data
{
    [Required]
    [Display(Name = "Contact Group")]
    public SelectList contactGroupsList { get; set; }

    [Required]
    [Display(Name = "Contact Name")]
    public string contactName { get; set; }

    [Required]
    [Display(Name = "Contact Person Name")]
    public string contactPicName { get; set; }
}

**my.cshtml**
@Html.DropDownListFor(x => x.contactGroupsList, 
    Model.contactGroupsList, "", 
    new { @id = "contactGroupsList", 
    @class = "form-select" })
<span asp-validation-for="contactGroupsList" class="text-danger"></span>


**Controller**

 if (!ModelState.IsValid)
 {
     var errors = ModelState.SelectMany(x => x.Value.Errors.Select(e => new { Field = x.Key, ErrorMessage = e.ErrorMessage }));
     return Json(new { result = false, errors = errors, message = "" });
 }
``

Community Center Not monitored
{count} votes

3 answers

Sort by: Most helpful
  1. Dondon510 261 Reputation points
    2025-04-10T11:26:44.5966667+00:00

    @AgaveJoe

    So do you have any idea how to deal with this?, we start the @Html.DropDownListFor to avoid user to select the 1st option, user might accidentally select it so that's why I put "" but we have to check if they select the empty ones.

    my.cshtml

    @Html.DropDownListFor(x => x.contactGroupsList, Model.contactGroupsList, "", new { @id = "contactGroupsList", @class = "form-select" }) <span asp-validation-for="contactGroupsList" class="text-danger"></span>
    
    0 comments No comments

  2. AgaveJoe 30,126 Reputation points
    2025-04-10T12:26:46.8033333+00:00

    So do you have any idea how to deal with this?

    To put it simply, when using HTML helpers like DropDownListFor, you need to understand how they create HTML <select> elements. This involves two key parts:

    1. The visible choices (options): These are the items the user sees in the dropdown list.
    2. The chosen value (selected value): This is the value that gets submitted when the form is sent.

    The name attribute of the DropDownListFor corresponds to the property in your model that has the [Required] attribute. This property holds the selected value. The options themselves are just a collection of items used to build the dropdown list.

    Model

    public class ContactListModel
    {
        [Required]
        public string SelectedContact { get; set; }
    }
    
    
    

    View

    @model MvcDemo.Models.ContactListModel
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    <div class="container">
        <form method="post">
            <div>
                @Html.DropDownListFor(model => model.SelectedContact, (SelectList)ViewBag.ContactGroupsList)
                @Html.ValidationMessageFor(model => model.SelectedContact)
            </div>
            <div>
                <input type="submit" value="submit" name="submit"/>
            </div>
        </form>
    </div>
    
    

    Controller

    public class HtmlSelectExampleController : Controller
    {
        private SelectList contactGroupsList {get;set;}
    
        // GET: HtmlSelectExample
        [HttpGet]
        public ActionResult Index(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                id = string.Empty;
            }
            ContactListModel model = new ContactListModel() { SelectedContact = id };
            ViewBag.ContactGroupsList = PopulateOptions();
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(ContactListModel model)
        {
            ViewBag.ContactGroupsList = PopulateOptions();
            if (!ModelState.IsValid)
            { 
                return View();
            }
            return RedirectToAction("Index", "HtmlSelectExample", new { id= model.SelectedContact});
        }
    
    
        private SelectList PopulateOptions()
        {
            return new SelectList(new List<SelectListItem>
            {
                new SelectListItem { Text = "--Select--", Value = "" },
                new SelectListItem { Text = "Option 1", Value = "1" },
                new SelectListItem { Text = "Option 2", Value = "2" },
                new SelectListItem { Text = "Option 3", Value = "3" }
            }, "Value", "Text");    
        }
    }
    
    
    0 comments No comments

  3. Dondon510 261 Reputation points
    2025-04-10T13:01:19.08+00:00

    Hi @AgaveJoe

    I try this, but the SelectList still claimed as empty although I don't set it as required as the snippet code below

    @Html.DropDownListFor(x => x.selectedContactGroup, 
        Model.contactGroupsList, "", 
        new { @id = "contactGroupsList", 
        @class = "form-select" })
        <span asp-validation-for="selectedContactGroup" class="text-danger"></span>
    
    [Required]
    [Display(Name = "Contact Group")]
    public string selectedContactGroup { get; set; }
    
    public SelectList contactGroupsList { get; set; } 
    
    
    Controller
    
    if (!ModelState.IsValid)
    {
        var errors = ModelState.SelectMany(x => x.Value.Errors.Select(e => new { Field = x.Key, ErrorMessage = e.ErrorMessage }));
        return Json(new { result = false, errors = errors, message = "" });
    }
    
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.