Article

Validate a dropdownlist in ASP.Net Core MVC

In this article we will learn Validate a dropdownlist in ASP.Net Core MVC.

We want to make Deparment dropdownlist field of Model Employee Class required. If the required values are not provided and the form is submitted we want to display required validation errors as shown below.

validate-dropdownlist-asp-net-core-mvc

Learn step by step Validate a dropdownlist in ASP.Net Core MVC.
Validation logic is added to the Employee model. You ensure that the validation rules are enforced any time a user creates a Employee.

Add validation rules to the Employee model

To make Department field a required field, apply Required attribute on the property of the Employee model class. Required attribute is in System.ComponentModel.DataAnnotations namespace.

Add this namespace for Add validation to an ASP.NET Core MVC app

System.ComponentModel.DataAnnotations

Empoyee.cs :Update the Employee class

The Select List is bound to Department property of the Employee model class. To make the Department Select List required, apply [Required] attribute on the Department property of the Employee class.
If you make the Department property, a nullable property by including a question mark then the [Required] attribute is needed to make the field a required field.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace EmplloyeeManagement.Models
{
    public class Employee
    {
        public int Id { get; set; }
        [Required]
        public Dept? Department { get; set; }

    }
}

Key Point:
Let’s first understand why we are making Dept Nullable. If you are not making Nullable, we are getting this error – The value ” is invalid.

validate-dropdownlist-asp-net-core-mvc

The datatype of the Department property is Dept enum.
By default an enum data type is int.
An empty string is set as the value for Select Department option of the select list in the HTML.
So when this option Please Select is selected from the select list, the value empty string is used as the value for Department property whose underlying data type is int. Obviously an empty string is not a valid value for int. This is the reason we get – The value ” is invalid.

Add one Dept.cs class in model folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EmplloyeeManagement.Models
{
    public enum Dept
    {
        None,
        HR,
        Networking,
        Developer
        
    }
}

The Department select list is bound to the following Dept enum.

How validation works to an ASP.NET Core MVC app

The following code shows the two Create methods.

 [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(Employee employee)
        {
            if (ModelState.IsValid) { 
            Employee newEmployee = _employeeRepository.Add(employee);
            return RedirectToAction("Details", new { id = newEmployee.Id });
             }
            return View();
        }

The first (HTTP GET) Create action method displays the initial Create form. The second ([HttpPost]) version handles if the form post. The second Create method (The [HttpPost] version) calls ModelState.IsValid to check whether the employee has any validation errors. Calling this method evaluates any validation attributes that have been applied to the object. If validation has failed we return the same view so the user can provide the required data and resubmit the form.

Create.cshtml view template is shown in the following markup:

@model Employee

@{ 
    ViewBag.Title = "Create Employee";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<form asp-controller="home" asp-action="Create" method="post" class="mt-3">
  
    <div class="form-group row">
        <label asp-for="Department" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <select asp-for="Department" class="custom-select mr-sm-2" asp-items="Html.GetEnumSelectList<Dept>()">
         <option value="">Select Department</option>
           </select>
            <span asp-validation-for="Department" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Create</button>
        </div>
    </div>
</form>

To display validation errors use asp-validation-for tag helpers. This asp-validation-for tag helper displays a validation message for a single property of our Eployee model class.

To display the validation error associated with the Department property of the Employee class use asp-validation-for tag helper on a element as shown above.

Leave a Reply

Your email address will not be published. Required fields are marked *