selectlist asp.net core code example
Example 1: class selector to property in asp net core dropdown
<select data-val="true" data-val-required="The Employee field is required." id="Employee" name="Employee"> <option value=""></option> <optgroup label="IT"> <option value="1">Mike</option> </optgroup> <optgroup label="Sales"> <option value="2">Pete</option> <option value="4">Dean</option> </optgroup> <optgroup label="Admin"> <option value="3">Katy</option> </optgroup></select>
Example 2: asp.net core selectlist
In Library:
public static class UI_Data
{
public static string[] QuestionsArray = {
"Question 1",
"Question 2",
"Question 3"
};
}
In Model:
public string UserQuestionNumber { get; set; } = "";
In View:
<select asp-for="UserQuestionNumber">
@for (int i = 0; i < UI_Data.QuestionsArray.Length; ++i)
{
<option value=@i.ToString()> @UI_Data.QuestionsArray[i] </option>
}
</select>
In Controller:
try
{
int questionNumber = Int16.Parse(userModel.UserQuestionNumber);
...
}
catch (Exception error)
{
return View();
}