Reputation: 45
I'm trying to make the City
attribute a dropdownlist attribute which is populated by my local sql server. What should I change in my code?
By the way, I'm using ASP.NET Core 3.1 and a local SQL Server database in my project. And please answer with Razor Pages format, not MVC format.
My Person
class:
public class Person
{
[Key]
public int ID { get; set; }
public string City { get; set; }
}
Inside of Models/Person/create.cshtml
:
<div class="form-group">
<label asp-for="Person.City" class="control-label"></label>
<input asp-for="Person.City" class="form-control" />
<span asp-validation-for="Person.City" class="text-danger"></span>
</div>
Inside of Models/Person/edit.cshtml
:
<div class="form-group">
<label asp-for="Person.City" class="control-label"></label>
<input asp-for="Person.City" class="form-control" />
<span asp-validation-for="Person.City" class="text-danger"></span>
</div>
Upvotes: 2
Views: 2363
Reputation: 18159
Here is a demo:
public class ListModel : PageModel
{
[BindProperty]
public SelectList Cities { get; set; }
[BindProperty]
public Person Person { get; set; }
public void OnGet()
{
Cities = new SelectList(_context.Cities.ToList(), "City", "City");
}
}
cshtml:
<select asp-for="Person.City" [email protected] ></select>
Upvotes: 2
Reputation: 874
May be you can try something like this in the view file :
<select asp-for="Person.CityId" class="form-control"
asp-items="ViewBag.CityId"></select>
and in the Razor Page or Controller use something like this.
ViewData["CityId"] = new SelectList(_context.Cities,
"CityId", "CityId", Person.CityId);
You can adapt this code with your model. This is working in my MVC project, so I thing you can easily adapt it to Razor Page.
Upvotes: 0