Below I present a select with a label were in this case the select is populated using the following model.
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString() => Name;
}
Index page with the above select
public class IndexModel : PageModel
{
public List<SelectListItem> Options { get; set; }
[BindProperty]
public int SelectedCategory { get; set; }
private readonly IOptions<List<Category>> _categories;
public IndexModel(IOptions<List<Category>> categories)
{
_categories = categories;
}
public void OnGet()
{
Options = _categories.Value.Select(category => new SelectListItem()
{
Value = category.Id.ToString(),
Text = category.Name
}).ToList();
}
public RedirectToPageResult OnPost(int id)
{
return RedirectToPage("Results", new
{
sender = _categories.Value.FirstOrDefault(x => x.Id == id)!.Name
});
}
}
Index front end code
<div class="container">
<div class="alert alert-primary shadow mt-2 mb-4" role="alert">
<h1 class="fs-6 text-center">Reading list from settings</h1>
</div>
<form id="main" method="post">
<div class="input-group">
<label asp-for="SelectedCategory">Categories
<select name="Id"
asp-for="SelectedCategory"
class="form-select"
style="width: 9.2em"
asp-items="Model.Options">
</select>
</label>
<input type="submit"
value="Save"
class="btn btn-primary ms-2"/>
</div>
</form>
</div>
OnPost we direct to Results page
@page
@model ReadListApplication.Pages.ResultsModel
@{
}
<div class="alert alert-primary shadow mt-2 mb-4" role="alert">
<h1 class="fs-6 text-center">Posted from Index page</h1>
</div>
Selected Category <span class="text-danger">@Model.CategoryName</span>
Back end
public class ResultsModel : PageModel
{
[BindProperty]
public string CategoryName { get; set; } = string.Empty;
public void OnGet(string sender)
{
CategoryName = sender;
}
}
Full source https://github.com/karenpayneoregon/razor-pages-IOptions-samples/tree/master/ReadListApplication