xxxxxxxxxx
public class IndexModel : PageModel
{
private readonly List<Fruit> _fruitList = new()
{
new Fruit { Id = "1", Name = "Banana", Price = 200 },
new Fruit { Id = "2", Name = "Apple", Price = 47 },
new Fruit { Id = "3", Name = "Orange", Price = 75 },
new Fruit { Id = "4", Name = "Lemon", Price = 123 },
};
[BindProperty]
public string SelectedFruit { get; set; } = "1";
public int? SelectedFruitPrice =>
_fruitList.FirstOrDefault(x => x.Id == SelectedFruit)?.Price;
public SelectList Options { get; set; }
public void OnGet()
{
Options = new SelectList(_fruitList, "Id", "Name");
}
public void OnPost()
{
Options = new SelectList(_fruitList, "Id", "Name");
}
}
xxxxxxxxxx
public class Fruit
{
public string Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
xxxxxxxxxx
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="row">
<div class="col-4">
<form method="post">
<div class="mb-3">
<select onchange="this.form.submit()" asp-for="SelectedFruit" class="form-control" asp-items="@Model.Options"></select>
</div>
</form>
<input class="form-control" value="@Model.SelectedFruitPrice" />
</div>
</div>