I'm trying to pull the list of countries from the database table, but there are no resultset showing, and there are data in the table. The below is what i've done. Although, I'm using the InputSelect field for the first time, so I don't have the full understanding of it yet. I was able to pull data using this with the input Text. So it looks like my database connection string is fine.
//Razor Page
@inject ICountryData _db
<h1>Choose a Country</h1>
<h4>Countries</h4>
@if (Countries is null)
{
<p><em>Loading...</em></p>
}
else
{
<div class="col-6">
<EditForm Model="@DisplayCountry">
<div class="form-group">
<label class="col-2 font-weight-bold">CountryName:</label>
<InputSelect @bind-Value="DisplayCountry.CountryName" class="form-control">
<option value="">Select</option>
@foreach (var person in Countries)
{
<option value="@DisplayCountry.CountryName"> @DisplayCountry.CountryCode </option>
}
</InputSelect>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</EditForm>
</div>
}
@code {
private List<CountryModel> Countries;
private DisplayCountryModel DisplayCountry = new DisplayCountryModel();
protected override async Task OnInitializedAsync()
{
Countries = await _db.GetCountry();
}
private async Task InsertCountry()
{
CountryModel C = new CountryModel
{
CountryCode = DisplayCountry.CountryCode,
CountryName = DisplayCountry.CountryName,
};
await _db.InsertCountry(C);
Countries.Add(C);
DisplayCountry = new DisplayCountryModel();
}
}
using DataAccessLibrary.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DataAccessLibrary
{
public class CountryData : ICountryData
{
private readonly ISqlDataAccess _db;
public CountryData(ISqlDataAccess db)
{
_db = db;
}
public Task<List<CountryModel>> GetCountry()
{
string sql = "select * from dbo.Country";
return _db.LoadData<CountryModel, dynamic>(sql, new { });
}
public Task InsertCountry(CountryModel Country)
{
string sql = @"insert into dbo.Country (CountryCode, CountryName)
values (@CountryCode, @CountryName);";
return _db.SaveData(sql, Country);
}
}
}
The @foreach
variable is wrong. I rewrote it as the below and it worked.
<InputSelect @bind-Value="DisplayCountry.CountryName" class="form-control">
<option value="">Select</option>
@foreach (var item in Countries)
{
<option value="@item.CountryCode"> @item.CountryName </option>
}
</InputSelect>