问题描述
目前,我与ASP.Net MVC 6个工作使用EF7。我使用的是默认的控制器生成。出于某种原因,我的下拉列表不与,即使数据present在创建或编辑页面上的数据填充。
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.
只是为了澄清3选择列表正在由该都连接到主台我加入到3个不同的表填充。
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.
下面是我得到的。
控制器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();
}
查看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?
推荐答案
您既需要一个属性绑定到(选择的值)和选项的财产,他们需要有不同的名称。理想情况下,你应该使用视图模型这将对(说)
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; }
....
和get方法
public IActionResult Create()
{
SchoolVM model = new SchoolVM
{
DistrictList = new SelectList(_context.Districts, "DistrictId", "District"),
.....
};
return View(model);
}
和视图
@model SchoolVM
....
<select asp-for="DistrictId" asp-items="Model.DistrictList"></select>
另外,你可以使用 ViewBag
或的ViewData code>和使用
<select asp-for="DistrictId" asp-items="ViewBag.DistrictList"></select>
这篇关于Dropdownlists不与3个独立的参照表的数据填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!