5

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();
    }

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

How does PopulateCountries() get called?
@Mike I don't remember the details anymore, but I guess you can add PopulateCountries() in the PageLoad or some other page event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.