How to validate Dropdownlist in MVC 5 using model


In this post we will learn how to validate Dropdownlist using Model in MVC 5

First create model as follows

Model:

Model
    public class CountryModel
    {
        [Required(ErrorMessage="Country Required.")]
        public int SelectedCountryId { get; set; }
        public System.Web.Mvc.SelectList Countries { get; set; }
    }

 

In the model we have added the following line

[Required(ErrorMessage="Country Required.")]

Required is a attribute applied on SelectedCountryId.

this Required attribute is available in the namespace

using System.ComponentModel.DataAnnotations;

Required attribute force the user to send SelectedCountryId to the server, otherwise it will display the error message mentioned in the model as follows

(ErrorMessage="Country Required.")

Now write the action method in controller as follows

Action Method
        public ActionResult Index(CountryModel model)
        {
            if (model.Countries == null)
            {
                model.Countries = new SelectList(new List<SelectListItem>()
                {
                    new SelectListItem() { Text= "India", Value = "1" },
                    new SelectListItem() { Text= "Australia", Value = "2"}
                },"Value","Text");
            }
            return View(model);
        }

 

Add the view for the above action method and write the following code in it.

View
@model MVCControls.Models.CountryModel
@{
    ViewBag.Title = "Index";
}
<h2>Dropdownlist Validation</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    @Html.Label("Country")
    @Html.DropDownListFor(c => c.SelectedCountryId,Model.Countries, "..Select..")
    @Html.ValidationMessage("Country is required.");
    <input type="submit" name="name" value="Submit" />
}

Now rebuild the application and Run

image

image

image

Advertisements

One thought on “How to validate Dropdownlist in MVC 5 using model

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s