I want my web page to do in this way: when web page loads, all the radio button values should be fetched from database and shown in web page. This is a part of my ".cshtml" code:
<div class="radiobtn">
<label for="koobideh">select</label>
<input type="radio" id="koobideh" name="0" value="004" runat="server">
</div>
Here is a part of my ".cs" file:
public void OnGet()
{
string sql = "SELECT foodId FROM [reservation] WHERE userId = '" + UserId + "'" +
"AND date = '" + date + "'";
using (SqlCommand command = new SqlCommand(sql, connection))
{
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
string foodid = reader.GetString(reader.GetOrdinal("foodId"));
???????????????
}
reader.Close();
}
}
So when the web page is loaded for the first time, the input radios should be fetched from database and loaded in the correct place.
My first try was this:
Request.Form["0"] = reader.GetString(reader.GetOrdinal("foodId"));
But this is impossible since Request.Form is "ReadOnly". How can I do such a thing?
I have the "name" properties of input radios. I want to read the value of each group from database and make the radio as checked in the front side.
This May help. Here is an example of how you can show the chosen radio
based on the retrieved value from DataBase.
This is the .cshtml
code:
<label>
<input asp-for="Gender" type="radio" value="male">
<label for="male">Male</label>
</label>
<label>
<input asp-for="Gender" type="radio" value="female">
<label for="female">Female </label>
</label>
in the .cs file
[BindProperty]
public string Gender { get; set; }
public async Task<IActionResult> OnGetAsync()
{
Gender = await GetPersonGender(personId);
return Page();
}
//This Method to extract the Gender value of a person from DB.
private async Task<string> GetPersonGender( string personId)
{
string personGender = "";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using var command = new SqlCommand(
"SELECT * FROM Persons WHERE PersonId = @id", connection);
command.Parameters.AddWithValue("@id", personId);
using var reader = command.ExecuteReader();
if (reader.Read())
{
personGender = reader["Gender"].ToString();
}
}
return personGender;
}