1

I'm having problems trying to validate a drop down list, I've looked at similar questions on here and tried the suggestions but still no luck. One I haven't tried is making my Benefit Id nullable, but is that a good idea? many thanks

Model I'm trying to validate:

public class Benefit
{
public int Id { get; set; }
public string Name { get; set; }


}

View model:

public class LookupVm
{
    public SelectList Benefits { get; set; }
}

Controller set up:

var model = new LookupVm
{

    Benefits = new SelectList(_repository.Benefits.OrderBy(n => n.Name).ToList(), "Id", "Name")
}

The view:

        @Html.DropDownListFor(benefits => Model.Benefits.SelectedValue, Model.Benefits, "-Select-")
        @Html.ValidationMessageFor(benefits => Model.Benefits.SelectedValue)
Greg Smith
  • 2,449
  • 2
  • 24
  • 37
Michael Harper
  • 1,531
  • 2
  • 25
  • 42
  • http://beyondrelational.com/modules/24/syndicated/391/Posts/14810/dropdownlist-validation-in-aspnet-mvc-3razor.aspx – Antarr Byrd Dec 30 '12 at 19:32
  • You need to be more specific about the problem you're having - is there an error message? Invalid inputs are accepted? Please expand. – Greg Smith Dec 30 '12 at 20:12
  • Hi, My drop down lists are accepted even when empty, I want the validation to stop empty/null selections and display a validation error – Michael Harper Dec 30 '12 at 20:36

1 Answers1

2

You can add a SelectedBenefit property to you view model

public class LookupVm
{
    public int SelectedBenefit { get; set;}
    public SelectList Benefits { get; set; }
}

Then add on top of the view

@model LookupVm

And then dropdown list must be something like this:

@Html.DropDownListFor(model => model.SelectedBenefit, model.Benefits, "-Select-")
@Html.ValidationMessageFor(model => model.SelectedBenefit)

You will get the selected id on SelectedBenefit property and it will be a required field.

Esteban Elverdin
  • 3,552
  • 1
  • 17
  • 21
  • Hi Estaban, I followed your example and still get no validation on the drop down :( – Michael Harper Dec 30 '12 at 22:19
  • My lookupvm does have other select lists, would this cause confusion for "SelectedBenefit"? – Michael Harper Dec 30 '12 at 22:27
  • I don't think so. Did you enable client side validation? That is add jquery-1.7.1.min.js, jquery.validate.min.js, jquery.validate.unobtrusive.min.js and jquery.unobtrusive-ajax.min.js. Also need to add two properties in app.setting. Check http://stackoverflow.com/questions/11326792/asp-net-mvc-3-and-jquery-unobtrusive-ajax-min-js – Esteban Elverdin Dec 30 '12 at 22:30
  • Ahhhh, I thought client side validation was enabled by default DOH thank you so much, now everything works! :D – Michael Harper Dec 30 '12 at 22:40