The first value in my dropdown appears selected. I do not want this, I want the value in the row I selected to appear in my dropdown. Can anyone check my codes and help me with this?
I have a table where I display user data and a modal to update the user’s information. When I click the “Update” button, the modal opens, but the first value in my dropdown is always selected by default. However, I want the role value from the selected row to appear in the dropdown.
Here’s my code:
$('#usersUpdateModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var id = button.data('id');
var role = button.data('role');
var modal = $(this);
// Populate the input fields with the selected row's data
modal.find('input[name="users.Id"]').val(id);
modal.find('select[name="users.Role"]').val(role); // Here is where the role should be selected
});
@foreach (var k in Model.users)
{
<tr class="text-nowrap">
<td>@k.Id</td>
<td>@k.Role</td>
<td>
<button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#kullaniciGuncelleModal" data-id="@k.Id" data-role="@k.Role">
Güncelle
</button>
</td>
</tr>
}
<div class="row mb-3">
<div class="col-md-5">
<label class="col-form-label">Role</label>
</div>
<div class="col-md-7">
<select asp-for="users.YetkiId" class="form-select" required>
@foreach (var y in Model.yetkiler)
{
<option value="@y.Id">@y.Role</option>
}
</select>
</div>
</div>
[enter image description here](https://i.sstatic.net/AsK52b8J.jpg)
The roles in the dropdown are pulled from the “Yetki” table, which contains role information.
YetkiId is a foreign key (FK).
What could be causing the first value to always appear selected, and how can I fix this so the selected row’s role appears in the dropdown when the modal opens?