Hi there,
I am fetching a record from the DB and displaying it in a razor view. The text fields bind successfully, however the dropdown lists do not - they do not auto-select the item in the dropdown list that matches the DB record.
I know in plain MVC, when building a List<SelectListItem>, you can set the Selected property to true and when the view renders, this item will be auto-selected in the list.
Is this possible?
Backend Code:
var user = await _dbContext.Users.AsNoTracking().FirstOrDefaultAsync(x => x.Id == query.Id, cancellationToken);
var contractTypes = _dbContext.ContractTypes
.AsNoTracking()
.ToList()
.Select(x => new SelectListItem
{
Text = x.Description,
Value = x.Id.ToString(),
Selected = x.Id == user.ContractTypeId
});
return contractTypes;
View:
<div class="mt-2">
@(
Html.EJS()
.DropDownList("contractTypes")
.DataSource(Model.ContractTypes)
.Fields(new DropDownListFieldSettings { Text = "Text", Value = "Value" })
.Placeholder("Employment Contract Type")
.HtmlAttributes(new Dictionary<string, object>
{
{ "name", "User.ContractTypeId" }
})
.Render()
)
</div>
Result:
Kind regards,
Charles