John McCloskey
John McCloskey

Reputation: 117

MVC2 Html.DropDownList with required field and validation

I am having heaps of trouble populating a simple drop down box in MVC2. The drop down is a required field so needs validation for this. I will also need to know which option the user selected when the form is posted back.

If anyone has some code snippets for this I would love to see them.

Thanx

Upvotes: 1

Views: 1869

Answers (1)

John McCloskey
John McCloskey

Reputation: 117

Got it working. Here is some code snippets:

VIEW MODEL: public IEnumerable NRCTypeSelect { get; set; }

[Range(1, Int32.MaxValue, ErrorMessage="Required Field")] public int SelectedNCRType { get; set; }

CONTROLLER: model.NRCTypeSelect = NCRTypes.ToSelectList("Id", "Name");

EXTENSION METHOD: public static SelectList ToSelectList(this IEnumerable collection, string dataValueField, string dataTextField) { return new SelectList(collection, dataValueField, dataTextField); }

VIEW: <%= Html.DropDownListFor(x => x.SelectedNCRType, Model.NRCTypeSelect, "Select...") %> <%= Html.ValidationMessageFor(model => model.SelectedNCRType, "Required Field") %>

Upvotes: 1

Related Questions