简体   繁体   中英

using a drop-down list to select a value for a model

Using MVC 4, Razor

I have a model like this:

public class Device
{
[Required]
public string TYPE {get; set;}
}

I need to get the value of TYPE from user in a form, but they are limited to 3 values, "A" , "B" , "C"

How do i enforce/do this in the View section?

Right now I have:
@Html.EditorFor(model => model.TYPE)
but this will allow the user to write in anything they want

The easiest way

@Html.DropDownListFor(model => model.TYPE, 
new List<SelectListItem>
    {
        new SelectListItem { Text = "A", Value = "A" },
        new SelectListItem { Text = "B", Value = "B" },
        new SelectListItem { Text = "C", Value = "C" },
    })

You are better off using a DropDownListFor and letting the user select from the available values. First create an enum for TYPE:

public enum PickType
{
    "A",
    "B",
    "C",
}

Then in your View:

@Html.DropDownListFor(model=>model.TYPE, new SelectList(Enum.GetValues(typeof(PickType))))

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