-1

I am new to MVC, as part of my work i need to validate drop down list with required field validation, i tried in below way but Validation not working, When i click on submit button without selecting a dropdown menu Validation is not working.

Model:

[Required(ErrorMessage = "*Required")]
[Display(Name = "Environment")]
public int? Environment { set; get; }

Controller:

List<SelectListItem> environmentlist = new List<SelectListItem>();
environmentlist.Add(new SelectListItem { Text = "SIT", Value = "1" });
environmentlist.Add(new SelectListItem { Text = "UAT", Value = "2" });
environmentlist.Add(new SelectListItem { Text = "PROD", Value = "3" });
ViewBag.EnvironmentList = environmentlist;

View:

@Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, String.Empty)
@Html.ValidationMessageFor(model => model.Environment)
tereško
  • 58,060
  • 25
  • 98
  • 150
Alex
  • 9
  • 1
  • 5
  • What is not working? The code you have shown will work fine (If you select the first option, you will get a validation error) –  Feb 05 '16 at 09:52
  • but i am not getting error, it is firing click event – Alex Feb 05 '16 at 09:54
  • What click event? Validation is not fired on a click event, its fired when a value in a form control is changed or a form is submitted. Show the relevant code. –  Feb 05 '16 at 09:56
  • Edit your question (not in comments) –  Feb 05 '16 at 10:02
  • 1
    Are you checking whether the model sent back is valid? If it's not, you would reload the form and the validation messages would show.. In your controller action you would have something like this.. if (ModelState.IsValid) { ... do the work.... } – Emma Middlebrook Feb 05 '16 at 10:03
  • This can be help [Click](https://msdn.microsoft.com/en-us/library/ee256141%28v=vs.100%29.aspx), With an [example](http://www.asp.net/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs) – Smit Patel Feb 05 '16 at 10:07

2 Answers2

0

This can be help in your code,

Public ActionResult yourMethod()
{
     if (ModelState.IsValid)
     {
        // Your code
     }
     else
     {                
        return View("Same View");
     }  
}

Learn more about ModelState.IsValid.

Community
  • 1
  • 1
Smit Patel
  • 2,992
  • 1
  • 26
  • 44
0

Try the following

 @Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, new {required = "required"})