Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate dropdownlist In ASP.NET Core 2.0 Razor page

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();
    }
like image 624
saeef ahmed Avatar asked Feb 07 '18 02:02

saeef ahmed


1 Answers

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

like image 155
luizs81 Avatar answered Oct 12 '22 03:10

luizs81