Search code examples
c#asp.net-core.net-coredropdown

How to get selecteditem of a ASP.Net core select element


I have a List<Incident> which I get by calling an API and use it to populate a select element in a ASP.Net core MVC app. I would like to get the selected Incident and display the value of its Option property in a label.

In the View I have the following:

@model List<Incident>
@{
    var incidents = (List<Incident>)ViewData["incidents"];
    ViewData["Title"] = "Dashboard";
}

<select class="browser-default custom-select mb-2">
    <option selected>Open this select menu</option>
    @foreach (var incident in @incidents)
    {
        <option value="@incident.id">@incident.Name</option>
    }
</select>

<div class="custom-control custom-checkbox mb-2">
    <input type="checkbox" class="custom-control-input" id="defaultUnchecked">
    <label class="custom-control-label" for="defaultUnchecked">@SelectedIncident.Option</label> CAN THIS BE DONE?
</div>

The controller's code is like this:

public async Task<IActionResult> Index()
{
    var incidents = await GetIncidentsAsync();
    ViewData[nameof(incidents)] = incidents;
    return View(incidents);
}

The incident class is:

public class Incident
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Option { get; set; }
    public string Description { get; set; }
    public string OtherDescription { get; set; }
}

Can this be done without a post-back to the server? Something like Syncfusion's DropDownList.


Solution

  • A simple method is to set the Option property value of each option to id attribute, and then use jquery to get the id of the selected item and assign it to lable

    <select class="browser-default custom-select mb-2" id="ddlIncidents">
      <option selected>Open this select menu</option>
      @foreach (var incident in @incidents)
      {
        <option id="@incident.Option" value="@incident.Id">@incident.Name</option>
      }
    </select>
    
    <div class="custom-control custom-checkbox mb-2">
      <input type="checkbox" class="custom-control-input" id="defaultUnchecked">
      <label class="custom-control-label" for="defaultUnchecked" id="selectedItem"></label>
    </div>
    
    @section Scripts
    {
     <script>   
      $("#ddlIncidents").change(function () {
        var value = $(this).children(":selected").attr("id");
        console.log(value);
        $("#selectedItem").text(value);
      });
    
     </script>
    }
    

    Result: enter image description here