but in the following example I have List<int> and why should I instantiate with new List<int>()? Why doesn't the model binder instantiate the SelectedCities here?
Model binding occurs when values are submitted to the Razor Page. It is not clear from your code sample if values are submitted to the City Razor Page.
I can only assume the GitHub code you are reviewing, fetches the selected IDs from a database. Since model binding is not taking place in this scenario, the List<T> must be instantiated before populating List<T> elements.
The model binder certainly has the ability to populate a List<T> when a collection is submitted as the example below illustrates.
public class CityModel : PageModel
{
[BindProperty]
public List<int> SelectedCities { set; get; }
public List<City> Cities = new List<City>
{
new City{ Id = 1, Name = "London"},
new City{ Id = 2, Name = "Paris" },
new City{ Id = 3, Name = "New York" },
new City{ Id = 4, Name = "Rome" },
new City{ Id = 5, Name = "Dublin" }
};
public void OnGet()
{
}
public void OnPost()
{
}
}
@page
@model RazorPagesDemo.Pages.CityModel
<form method="post">
<div>
<select asp-for="SelectedCities" asp-items="@(new SelectList(Model.Cities, "Id", "Name"))" multiple>
</select>
</div>
<div>
<input type="submit" value="submit" />
</div>
</form>
@{
}