问题
Currently I am working with ASP.Net MVC 6 using EF7. I am using the default controller generator. For some reason my drop downs are not populating with data on the create or edit page even though data is present.
Just to clarify the 3 select lists are being populated by 3 different tables that are all connected to the main table I am adding to.
Here's what I got.
Controller code
private readonly SchoolContext _context;
public SchoolsController(SchoolContext context)
{
_context = context;
}
public IActionResult Create()
{
ViewData["DistrictId"] = new SelectList(_context.Districts, "DistrictId", "District");
ViewData["LocationId"] = new SelectList(_context.Locations, "LocationId", "Location");
ViewData["TierId"] = new SelectList(_context.Tiers, "TierId", "Tier");
return View();
}
View code
@model School
is included at the top and here is what one of the select element looks like
<div class="form-group">
<label asp-for="DistrictId" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DistrictId" class ="form-control"></select>
</div>
</div>
The select lists are completely blank with no errors there is data.
This is all generated automatically so I am totally clueless on what went wrong. Any suggestions?
回答1:
You need both a property to bind to (the selected value) and a property for the options and they need to have different names. Ideally you should be using a view model which would have (say)
public class SchoolVM
{
public int DistrictId { get; set; }
public IEnumerable<SelectListItem> DistrictList { get; set; }
....
and in the GET method
public IActionResult Create()
{
SchoolVM model = new SchoolVM
{
DistrictList = new SelectList(_context.Districts, "DistrictId", "District"),
.....
};
return View(model);
}
and in the view
@model SchoolVM
....
<select asp-for="DistrictId" asp-items="Model.DistrictList"></select>
alternatively, you could use ViewBag
or ViewData
and use
<select asp-for="DistrictId" asp-items="ViewBag.DistrictList"></select>
回答2:
Assuming your view name is School (the convention for ViewModel is name of the view + "ViewModel")
class SchoolViewModel
{
IEnumerable<SelectListItem> Districts;
IEnumerable<SelectListItem> Locations;
IEnumerable<SelectListItem> Tiers;
}
Then in your view,
@model SchoolViewModel
...
@Html.DropDownList("Districts", m=>m.Districts, "-- Select--")
@Html.DropDownList("Locations", m=>m.Locations, "-- Select--")
@Html.DropDownList("Tiers", m=>m.Tiers, "-- Select--")
In your controller
public IActionResult Create()
{
var vm = new SchoolViewModel();
vm.Districts = _context.Districts.Select(d => new
{
Text = d.District,
Value = d.DistrictId.ToString()
};
//repeat for others...
return View(vm);
}
来源:https://stackoverflow.com/questions/34820483/dropdownlists-not-populating-with-data-from-3-separate-reference-tables