简体   繁体   中英

How to force a DropDownList value to be selected?

I have a DropDownList that gives me an output of:

<select name="MyFilter">
    <option value="">Choose an option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>

I want to force users to select one of the options with a value.

How do I do this? And what are the best ways of doing this? I know MVC has attributes like [Required], but you are not creating a new row in the database, rather you are updating one, so required could not work here (I think, I am not so familiar with attributes). Do I need a custom attribute?

I'm kinda just looking to be pointed in the right direction here as my googling has been fruitless so far...

Edit:

I have added:

[Required]
public SelectList MyFilter  { get; set; }

to the ViewModel, but it has not changed functionality. It still allows the form to go through. Could this be due to me adding in the "Choose an option" option in the view like this?

@Html.DropDownList("MyFilter", ((SelectList)Model.MyFilter), "Choose an option"

You need Required attribute applied to the property that will hold the selected value and not to the select list itself:

public class ViewModel
{
    public IList<SelectListItem> MyFilterValues  { get; set; }

    [Required]
    public int MyFilter  { get; set; }
}

Usage in the view:

@Html.DropDownListFor(m=>m.MyFilter, Model.MyFilterValues, "Choose an option")
@Html.ValidationMessageFor(m => m.MyFilter) 

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