简体   繁体   中英

MVC Dropdownlist with unselectable default item

I have a simple dropdown list that looks like this:

Please Select, Male, Female

The "Please Select" is selected by default (on create), but the user must select a value or the validation should fail.

What can I do to achieve this validation on the client-side? [Required] in the model does not seem to work.

Probably it would work if you check the value in the editor. Like:

return (!content.Equals("Please Select");

Unfortunately I'm unable to comment yet so I'll have to use this to suggest, please don't downvote just for that reason. But couldn't you make the dropdown list have 2 options: Male and Female and the default is just a set text, since the default is a text and not a SelectedIndex you could use that to validate. you would be able to see that it is set if (dropdownlist.SelectedIndex != -1) .

For validation, JavaScript or jQuery will be your friend. Especially for validation, you can do it a couple of ways. The approach I would take would be:

$('#drpExample').on('change', function () {
     var content = $(this).val();
     if(content === 'default') {
         // Default Selection, Display Error.
     }
});

jQuery really simplifies this quite a bit, as you can see.

You can make use of RegularExpression attribute, this way you will have validation on both client and server side.

[RegularExpression(@"\b(Male|Female)", ErrorMessage = "Please Select, Male, Female")]
public string Gender{ get; set; }
public class yourentity
{
     public SelectList GenderList { get; set; }
     [Required]
     public int gender { get; set; }
}

public ActionResult youraction()
{
    yourentity a = new yourentity();
    a.GenderList = new SelectList(new List<SelectListItem>
    {
        new SelectListItem { Text = "Male", Value = "1"},
        new SelectListItem { Text = "Female", Value ="2"},
    });
    return View(a);
}

In your view

@Html.DropdownListFor(m=>m.gender,m.GenderList ,"Select Gender")
@Html.ValidationMessagefor(m=>m.gender)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM