.NET Core <select> With Default Value?
The SelectList
constructor can take an additional argument, namely selectedValue
. In your case, you should be able to pass this through, which I think will look something like this:
asp-items="@(new SelectList(Model.AvailableForms, "Id", "Name", Model.SelectedForm.Id))"
I think the reason asp-for
isn't working for you is the mismatch between the value of SelectedForm.Name
(which is a string), and the value of the Id
property you're using in the SelectList
constructor (which is an integer?).
You can see partially how this works in the source code. You end up here in GenerateOption
:
var selected = item.Selected;
if (currentValues != null)
{
var value = item.Value ?? item.Text;
selected = currentValues.Contains(value);
}
At this point, I believe currentValues
will contain a single element, which will be a string (Form.Name
). I believe also that item.Value
will be e.g. "1"
and so there's no match.
Basically you need to is set the select to use the SelectedForm.Id
property, then specify the value of the form to be selected in your controller. I had to update your code a little but this works for me -
<label asp-for="SelectedForm" class="form-control-label font-weight-bold"></label>
<select asp-for="SelectedForm.Id"
class="form-control"
onchange ="onFormSelected(this.value)"
asp-items="@(new SelectList(Model.AvailableForms, "Id", "Name"))">
</select>
Then in your controller
var vm = new ReportViewModel()
{
AvailableForms = new List<Form>()
};
var form2 = new Form() { Id = 2, Name = "Bar" };
(vm.AvailableForms as List<Form>).Add(new Form() { Id = 1, Name = "Foo" });
(vm.AvailableForms as List<Form>).Add(form2);
(vm.AvailableForms as List<Form>).Add(new Form() { Id = 3, Name = "Baz" });
vm.SelectedForm = form2;
return View(vm);