How to create ASP.Net MVC DropDownList with required validation

£可爱£侵袭症+ 提交于 2019-11-29 12:07:10

There are few ways to work with DropDownList. I personally like to use Strongly-Type ViewModel instead of ViewBag.

Screen Shot

Validation message displays when submit button is clicked without selecting Country.

Entity

public class Country
{
    public int Country_id { get; set; }
    public string Description { get; set; }
}

Model

public class CountryViewModel
{
    [Display(Name = "Country")]
    [Required(ErrorMessage = "{0} is required.")]
    public int SelectedCountryId { get; set; }

    public IList<SelectListItem> AvailableCountries { get; set; }

    public CountryViewModel()
    {
        AvailableCountries = new List<SelectListItem>();
    }
}

Controller

public class HomeController : Controller
{
    public ActionResult Create()
    {
        var countries = GetCountries();
        var model = new CountryViewModel {AvailableCountries = countries};
        return View(model);
    }

    [HttpPost]
    public async Task<ActionResult> Create(CountryViewModel countryViewModel)
    {
        if (ModelState.IsValid)
        {
            int countryId = countryViewModel.SelectedCountryId;
            // Do something
        }
        // If we got this far, something failed. So, redisplay form
        countryViewModel.AvailableCountries = GetCountries();
        return View(countryViewModel);
    }

    public IList<SelectListItem> GetCountries()
    {
        // This comes from database.
        var _dbCountries = new List<Country>
        {
            new Country {Country_id = 1, Description = "USA"},
            new Country {Country_id = 2, Description = "UK"},
            new Country {Country_id = 3, Description = "Canada"},
        };
        var countries = _dbCountries
            .Select(x => new SelectListItem {Text = x.Description, Value = x.Country_id.ToString()})
            .ToList();
        countries.Insert(0, new SelectListItem {Text = "Choose a Country", Value = ""});
        return countries;
    }
}

View

@model DemoMvc.Models.CountryViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>

    <h2>Create</h2>

    @using (Html.BeginForm())
    {
        <div class="form-group">
            @Html.LabelFor(model => model.SelectedCountryId, 
               new {@class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedCountryId, 
                    Model.AvailableCountries, new {@class = "form-control"})
                @Html.ValidationMessageFor(model => model.SelectedCountryId, 
                     "", new {@class = "text-danger"})
            </div>
        </div>

        <input type="submit" value="Submit"/>
    }

</body>
</html>

Firstly, you cannot get any client side validation using the overload of DropDownList() that you are using. You need to use a different name for the property your binding to and the SelectList. Change the controller code to (say)

ViewBag.CountryList = new SelectList(_db.Countries, "Country_id", "Description");

and change the model property attribute to (delete the RangeAttribute)

 [Required(ErrorMessage = "Error: Must Choose a Country")]
 public int Country_id { get; set; }

Then in the view use an overload that generates a null label option

@Html.DropDownListFor(m => m.Country_id, (SelectList)ViewBag.CountryList, "Choose a Country", new { @class = "form-control" })

If the user submits the form with the first ("Choose a Country") option selected, a validation error will be displayed.

Side note: It is recommended that you use a view model with a property public IEnumerable<SelectListItem> CountryList { get; set; } rather than ViewBag (and the view becomes @Html.DropDownListFor(m => m.Country_id, Model.CountryList, "Choose a Country", new { @class = "form-control" })

For .net core instead of @Html.ValidationMessageFor(...

Use

razor cshtml

<span asp-validation-for="SelectedCountryId" class="text-danger"></span>

model poco

[Required(ErrorMessage = "Country is required.")]
public int SelectedCountryId { get; set; }
Hafsal Rh

Model Class

        [Display(Name = "Program")]
        [Required, Range(1, int.MaxValue, ErrorMessage = "Select Program")]
        public string Programid { get; set; 

View

        @Html.DropDownListFor(Model=>Model.Programid,(IEnumerable<SelectListItem>)ViewBag.Program, new {@id = "ddlProgram"})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!