3 回答
TA贡献1807条经验 获得超9个赞
在第 2 个 foreach 循环中,您将添加到第 1 个列表中,而不是名为 list1 的第 2 个列表。更正如下:
public ActionResult Create()
{
var Sections = _context.Sections.ToList();
var Customers = _context.Customers.ToList();
List<SelectListItem> list1 = new List<SelectListItem>();
foreach (var item in Customers)
{
list1.Add(new SelectListItem { Text = item.Customer_Name, Value = item.Customer_Id.ToString() });
}
ViewBag.Customers = list1;
List<SelectListItem> list2 = new List<SelectListItem>();
foreach (var item in Sections)
{
list2.Add(new SelectListItem { Text = item.Section_Name, Value = item.Section_Id.ToString() });
}
ViewBag.Sections = list2;
return View();
}
TA贡献1851条经验 获得超5个赞
问题在于您的第二个 for-each 循环,您将其添加到实际上面向客户的第一个列表中。SelectListItem
此外,简化您的 GET 方法,如下所示。它将降低复杂性。Create
// GET: Contracts/Create
[HtttpGet]
public ActionResult Create()
{
var sections = _context.Sections.ToList();
var customers = _context.Customers.ToList();
ViewBag.SectionSelectList = new SelectList(sections,"Section_Id","Section_Name");
ViewBag.CustomerSelectList = new SelectList(customers,"Customer_Id","Customer_Name");
return View();
}
然后在视图中将 s 替换为以下内容:@Html.DropDownListFor
@Html.DropDownListFor(model => model.CustomerId, ViewBag.CustomerSelectList, "Select customers", new { @class = "form-control" })
@Html.DropDownListFor(model => model.SectionsId, ViewBag.SectionSelectList , "Select Sections", new { @class = "form-control" })
TA贡献1934条经验 获得超2个赞
试试这个:
// GET: Contracts/Create
public ActionResult Create()
{
var listOfCustomers = new List<SelectListItem>();
foreach (var item in _context.Customers.ToList())
{
listOfCustomers.Add(new SelectListItem { Text = item.Customer_Name, Value = item.Customer_Id.ToString() });
}
ViewBag.Customers = listOfCustomers;
var listOfSections = new List<SelectListItem>();
foreach (var item in _context.Sections.ToList())
{
listOfSections.Add(new SelectListItem { Text = item.Section_Name, Value = item.Section_Id.ToString() });
}
ViewBag.Sections = listOfSections;
return View();
}
- 3 回答
- 0 关注
- 113 浏览
添加回答
举报