DropDownList with required validation using Model in ASP.Net Core MVC

Last Reply one month ago By dharmendr

Posted one month ago

Without selecting Study and Scenario DDL, when I click on save button, I get validation message "Study is required", "Scenario is required".

Now, when I select Study item and Scenario item from dropdown, these validation messages don't disappear on dropdown selectedIndex and inside ActionMethod, I get ModelState.IsValid = false due to which I am unable to save the records even after selecting the dropdown items.

 

https://ibb.co/5YqGcBM

Please let me know after selecting items why validation message doesn't disappear?

ViewModel

public class MappingWellViewModel
{
    [Required(ErrorMessage = "Study is required")]
    public string StudyId { get; set; }
    public SelectList StudyList { get; set; }

    [Required(ErrorMessage = "Scenario is required")]
    public string ScenarioId { get; set; }
    public SelectList ScenarioList { get; set; }
}

Well.cshtml

Study :
<select class="form-control col-md-8" onchange="GetScenario(this.value);"
		asp-for="StudyId"
		asp-items="@Model.StudyList">
	<option value="">--Please Select--</option>
</select>
<span asp-validation-for="StudyId" class="text-danger"></span>
Scenario :
<select id="ddlScenario" class="form-control col-md-8" name="ddlScenario"
		asp-for="ScenarioId"
		asp-items="@Model.ScenarioList">
	<option value="">--Please Select--</option>
</select>
<span asp-validation-for="ScenarioId" class="text-danger"></span>
<button type="submit" class="btn dxButton float-right">Save</button>

Controller

[HttpPost]
public IActionResult Well(MappingWellViewModel mappingWellViewModel)
{
	try
	{
		if (ModelState.IsValid)
		{
			//save DDL selected values in DB
		}
		return Well();
	}
	catch(Exception ex)
	{
		throw ex;
	}
}

I am working on Asp.Net Core MVC 3.1

Thank you in advance.

Posted one month ago

Hi Richa,

Check this example. Now please take its reference and correct your code.

Model

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;

public class PersonModel
{
    [Required(ErrorMessage = "Name is required.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Country is required.")]
    public string Country { get; set; }
    public SelectList CountryList { get; set; }
}

Controller

public class HomeController : Controller
{
    public IActionResult Index()
    {
        PersonModel model = new PersonModel();
        model.CountryList = PopulateCountries();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(PersonModel person)
    {
        person.CountryList = PopulateCountries();
        if (ModelState.IsValid)
        {
            ViewBag.Name = person.Name;
            ViewBag.CountryName = person.Country;
        }

        return View(person);
    }

    private SelectList PopulateCountries()
    {
        List<SelectListItem> countries = new List<SelectListItem>();
        countries.Add(new SelectListItem { Text = "Select", Value = "" });
        countries.Add(new SelectListItem { Text = "USA", Value = "USA" });
        countries.Add(new SelectListItem { Text = "India", Value = "India" });
        countries.Add(new SelectListItem { Text = "Russia", Value = "Russia" });
        countries.Add(new SelectListItem { Text = "France", Value = "France" });
        SelectList items = new SelectList(countries, "Value", "Text");
        return items;
    }
}

View

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model DropDown_Model_Validation_Core_MVC.Models.PersonModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-4">
                <form asp-action="Index">
                    <div class="form-group">
                        <label asp-for="Name" class="control-label"></label>
                        <input asp-for="Name" class="form-control" />
                        <span asp-validation-for="Name" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Country" class="control-label"></label>
                        <select id="ddlCountries" name="Country" asp-items="@Model.CountryList" class="form-control"></select>
                        <span asp-validation-for="Country" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <input type="submit" value="Submit" class="btn btn-default float-right" />
                    </div>
                </form>
                @if (ViewData.ModelState.IsValid)
                {
                    <span>Name:</span> @ViewBag.Name;
                    <br />
                    <span>Country:</span> @ViewBag.CountryName;
                }
            </div>
        </div>
    </div>
</body>
</html>

Screenshot