I want to populate dropdownlist from my database.What is the way of model bind in razor page
public IActionResult OnGet()
{
var model = new Item
{
ItemTypes = _context.ItemTypes.ToList(),
Parts = _context.Parts.ToList(),
Sections = _context.Sections.ToList()
};
return Page();
}
At this point you probably got it sorted out, but if it can help future visitors:
In your PageModel
class, create one or more properties that will receive your "lists":
public class CreateModel : PageModel
{
...
public SelectList CountryList { get; set; }
...
}
Still in the same class, create a method that will populate your list and set your property:
private void PopulateCountries()
{
var countries = from c in _context.Countries
orderby d.Name
select c;
CountryList = new SelectList(countries, "Alpha3", "CountryName");
}
Then, in your page:
<div class="form-group">
<label asp-for="Race.CountryCode" class="control-label"></label>
<select asp-for="Race.CountryCode" class="form-control"
asp-items="@Model.CountryList">
<option value="">-- Select --</option>
</select>
</div>
Of course there are small variations you can do. For example, put the PopulateCountries
in a base class, in a service, etc., but I think you got the idea.
Reference: Razor Pages with EF Core in ASP.NET Core - Update Related Data - 7 of 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With