I have an edit page with razor page. I want the selected values in the database in select2 to be selected in select2. For this reason, I am trying to loop selected values and make them selected for select2. But this administration is not working.
<div class="mb-3" data-select2-id="21">
<select asp-for="SelectedCities" asp-items="ViewBag.CityPrices as SelectList" id="selected-cities" class="multiple-select select2-hidden-accessible" data-placeholder="Şehir Seçiniz" multiple="" data-select2-id="21" tabindex="-1" aria-hidden="true"></select>
</div>
here is my script
<script>
$(document).ready(function () {
@foreach (var packageCity in Model.PackageCities)
{
<text>
$('#selected-cities').val('@packageCity.CityPrice.PriceId');
$('#selected-cities').trigger('change');
</text>
}
</script>
Here is a simple example of how to set selected values in a select list:
Models:
public class Fruit
{
public int FruitId { get; set; }
public string Name { get; set; } = default!;
}
public class DemoViewModel
{
public List<int> SelectedFruit { get; set; } = default!;
}
HomeController.cs
:
[HttpGet]
public IActionResult Index()
{
// all items that should be in your select list
var fruitList = new List<Fruit>
{
new Fruit { FruitId = 1, Name = "Banana" },
new Fruit { FruitId = 2, Name = "Orange" },
new Fruit { FruitId = 3, Name = "Apple" },
new Fruit { FruitId = 4, Name = "Kiwi" },
};
// get from database the ids of the items that should be selected
var selectedFruit = new List<int> { 2, 3 };
// create MultiSelectList
ViewBag.FruitSelectList = new MultiSelectList
(
items: fruitList,
dataValueField: nameof(Fruit.FruitId),
dataTextField: nameof(Fruit.Name),
selectedValues: selectedFruit
);
return View();
}
[HttpPost]
public IActionResult Index(DemoViewModel model)
{
// save model.SelectedFruit to database
return RedirectToAction("Index");
}
View:
@model DemoViewModel
@{
ViewData["Title"] = "Home Page";
}
<form asp-controller="Home" asp-action="Index">
<div class="mb-3">
<select id="fruitSelect" class="form-control" asp-for="SelectedCities" asp-items="ViewBag.FruitSelectList"></select>
</div>
<button class="btn btn-primary">Submit</button>
</form>
@section Scripts {
<script>
$(document).ready(function () {
$('#fruitSelect').select2();
});
</script>
}
And here is a simple demo project.