I want to pass the value of the combobox to my variable in the model. Here is the code in the View:
<form method="post" asp-page-handler="Register">
<div >
<label asp-for="@Model.tournamentID"></label>
<select id="tournament" name="tournament" asp-for="tournamentID">
@if (Model.listOfTournaments != null)
{
foreach (var tournament in Model.listOfTournaments)
{
<option value="@tournament.id" selected="@(ViewBag.SelectedIndex==tournament.id?"selected":null)" >@tournament.id</option>
}
}
</select>
</div>
<div >info</div>
<div >message</div>
<div >checkbox</div>
<div >
<div >
<input type="submit" value="Register for Tournament" />
</div>
</div>
</form>
And the code in the Model:
TournamentManager tournamentManager = new TournamentManager();
public List<Tournament> listOfTournaments = new List<Tournament>();
[BindProperty]
public int tournamentID { get; set; }
public void OnGet()
{
foreach (Tournament t in tournamentManager.GetTournaments())
{
listOfTournaments.Add(t);
}
}
public void OnPost()
{
var id = Convert.ToInt32(User.FindFirst(x => x.Type == "ID").Value);
tournamentManager.RegisterPlayer(tournamentID, id);
}
After I select for example 8 in the combobox, I want in the model the tournamentID value to be also 8. How can I fix that?
CodePudding user response:
After I select for example 8 in the combobox, I want in the model the tournamentID value to be also 8.
Below is a work demo, you can refer to it.
public class IndexModel : PageModel
{
TournamentManager tournamentManager = new TournamentManager();
public List<Tournament> listOfTournaments = new List<Tournament>();
[BindProperty]
public int tournamentID { get; set; }
public SelectList ListOfTournaments { get; set; }
public void OnGet()
{
//foreach (Tournament t in tournamentManager.GetTournaments())
//{
// listOfTournaments.Add(t);
//}
listOfTournaments = new List<Tournament>
{
new Tournament{ id = 1},
new Tournament{ id = 2},
new Tournament{ id = 3},
new Tournament{ id = 4},
new Tournament{ id = 5},
new Tournament{ id = 6},
new Tournament{ id = 7},
new Tournament{ id = 8}
};
ListOfTournaments = new SelectList(listOfTournaments, nameof(Tournament.id), nameof(Tournament.id));
}
public void OnPost(int tournamentID)
{
//var id = Convert.ToInt32(User.FindFirst(x => x.Type == "ID").Value);
//tournamentManager.RegisterPlayer(tournamentID, id);
}
}
View:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<form method="post">
<div >
<select asp-for="tournamentID" asp-items="Model.ListOfTournaments">
<option value=""></option>
</select>
</div>
<div >info</div>
<div >message</div>
<div >checkbox</div>
<div >
<div >
<input type="submit" value="Register for Tournament" />
</div>
</div>
</form>
Result: