michael
michael

Reputation: 585

how to validate dropdown optionlist required functionality asp.net mvc

I have dropdown like this ,

<%= Html.OptionList("Worktype", new SelectList(new List<SelectListItem>{ 
new SelectListItem{Text = "--Select One--", Value = "0", Selected=true}, 
new SelectListItem{Text = "Fulltime", Value = "Full Time"}, 
new SelectListItem{Text = "Partime", Value = "Part Time"}}, "Value", "Text" )) %>

After selecting either fulltime or parttime it should submit, but because the default select is there, required validation is passing. I want the required validation for below two options. can anyone help me out.

thank you,

michael


Upvotes: 1

Views: 1668

Answers (3)

Aman Rohilla
Aman Rohilla

Reputation: 622

DO you want to fire any event only in case of full time and part time and in case of select you dont want anything to happen. If this is what you want

 $('#dropdownname').change(function () {
        var dropdownValue = $(this).val();
        if (dropdownValuetoString().length > 0)
        {
            Your Code here.........
        }
    });

dropdownname is the name of dropdown dropdownValue is what I m getting from dropdown list when index is changed. I was filling the dropdown from a list and I was not using any value field when u check the dropdownValue for select It will show blank and I m sure ur dropdown select list will always have a name. Tell me if it helps you else I will try something different

Upvotes: 0

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17794

I suggest that you should not be adding optional label in SelectList or as SelectListItem. you have overloads for Html.DropDown and Html.DropDownListFor that would allow you to insert an optional label at the top of your dropdown list. Pleas check my answer to this question.

Upvotes: 0

Eranga
Eranga

Reputation: 32447

SetValue empty instead of 0 for "--Select One--"

new SelectListItem{Text = "--Select One--", Value = string.Empty , Selected=true}

Upvotes: 1

Related Questions