Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core <select> With Default Value?

My goal is to generate a <select> dropdown with a certain select value (<option>) pre-selected, so the finalized HTML should look like this:

<select>
  <option value = "1">Option1</option>
  <option value = "2" selected>Option2</option>
  <option value = "3">Option3</option>
</select>

Note that the option with a value of 2 has a selected attribute, indicating that it will show before the dropdown is clicked. I cannot (and am trying to) achieve this using .NET Core Tag Helpers.

This is my model (I think you can safely ignore the details):

public class ReportViewModel
{
  [Display(Name = "Pick a form")]
  public IEnumerable<Form> AvailableForms { get; set; }

  public Form SelectedForm { get; set; }

  public List<ReportData> FormResponses { get; set; }
}

Note that the Form object there just has Id and Name properties on it.

This is my select statement:

<label asp-for="SelectedForm.Name" class="form-control-label font-weight-bold"></label>
<select asp-for="SelectedForm.Name"
        class="form-control"
        onchange ="onFormSelected(this.value)"
        asp-items="@(new SelectList(Model.AvailableForms, "Id", "Name"))">
</select>

I don't see the answer in the Microsoft Guide Or in a blog on the topic

like image 501
VSO Avatar asked Dec 13 '17 15:12

VSO


People also ask

How do I get the default value of select?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.


1 Answers

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);
like image 157
Tony Ranieri Avatar answered Oct 14 '22 19:10

Tony Ranieri