Can I specify the default option for an "asp-items" list directly in the .cshtml?
I have an ASP.Net Core form like this:
<div class="form-group" id="DW_Q30_div">
<label>@Questions.Q30*</label>
<select asp-for="Answers.Q30" asp-items="DropdownValues.DeployEnvironments"></select>
</div>
This is the corresponding Dropdown list:
public class DropdownValues
{
public static List<SelectListItem> DeployEnvironments { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "OnPremises", Text = "On Premises" },
new SelectListItem { Value = "Cloud", Text = "Cloud" }
};
...
Q: Is there any way I can specify the default item (for example, "Cloud" instead of "OnPremises") directly in the .cshtml markup itself?
As @LarryBud already commented change you code to this if you want select "Cloud" instead of "OnPremises:
public static List<SelectListItem> DeployEnvironments { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "OnPremises", Text = "On Premises" },
new SelectListItem { Value = "Cloud", Text = "Cloud" , Selected=true }
};
for your edit you can use this code:
var defaultValue=...your value from db.
foreach(var item in DeployEnviroments)
{
if item.Value==defaultValue item.Selected=true;
}