xralf
xralf

Reputation: 3642

In the model create enum from string value

How can I correct this model class, so that for the country_code field the user can choose in the view from the dropdown list the right country code (two letters) e.g. "EN", "FR", "DE" etc.

In the database it will be nvarchar(2), but via the web app, user could enter only what is in the dropdown list

public class Employee
{
    public int ID { get; set; }
    public string country_code { get; set; }
}

Upvotes: 1

Views: 60

Answers (1)

cvb
cvb

Reputation: 793

You need an enum for your country codes

enum country{
    EN,
    FR, etc...
}

Use enum in model

public class Employee
{
    public int ID { get; set; }
    public country country_code { get; set; }

}

Use enumdropdownlist

@Html.EnumDropDownListFor(model => model.country_code)

Then in the controller on save convert the enum to a string or save in database as enum value.

Another option would be to create another table and store all possible country codes in that table. Then pull that table's contents for the dropdown list.

Upvotes: 1

Related Questions