How to make MVC5 dropdownlist validationAsk Questions

 Posted on 08/16/2018

I'm trying to make a validation for my dropdownlist in MVC5 that user must select an item but I'm not sure how to do it. I've created my list inside the Model class for some reason and now I don't know how to apply [Require(ErrorMessage)] to this program

 

cshtml:

<label>Project Type:</label>
     @Html.DropDownListFor(m => m.Project_Type, Project1.Models.Dropdowns.GetProjectType(),"--Project Type--",

 new { @class = "form-control" })

<h6 style="text-emphasis-color:red;text-decoration-color:red" class="error">

 @Html.ValidationMessageFor(model => model.Project_Type)</h6>

Model:

 public static IEnumerable<SelectListItem> GetProjectType()
    {

    List<SelectListItem> Project_Type = new List<SelectListItem>();

    Project_Type.Add(new SelectListItem() { Text = "type1" });
    Project_Type.Add(new SelectListItem() { Text = "type2" });
    Project_Type.Add(new SelectListItem() { Text = "type3" });
    Project_Type.Add(new SelectListItem() { Text = "type4" });

    return Project_Type;
    }

it has an error when I apply [Require()] [error]image

Share On: facebook gplus twitter
profile
Asked by Hardik Bera on 08/16/2018 Score: 423 points
Add Comment:

Comments

1 Answers

1 Corrected Answers
Aproved Answers
3
Profile
Answered by Shailesh Chaudhary on 9/6/2018 7:43:12 AM Score: 713 points

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

Screen Shot

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

enter image description here

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>

Comments

Add Comment:

Post Your Answers

Existing Members

Sign in to your account
Email Address
Password
...or Join us
Download, Vote, Comment, Publish.
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.