从linq-sql语句填充下拉列表
本文关键字:下拉列表 填充 语句 linq-sql | 更新日期: 2023-09-27 18:25:19
我有两个不同的下拉列表,每个下拉列表都有一个select语句来返回正确的信息。遇到几个问题:
-
我应该以什么格式正确地返回select语句的结果?
-
我是否根据第一个下拉列表中所选项目的id来控制第二个下拉列表的select语句。
服务层:第一个下拉列表
public IEnumerable<ContentVw> GetSections()
{
using (var db = my connection info)
{
var sections = (from e in db.Table1
join re in db.RootTables re
on e.ID equals re.Table1ID
where re.ChairID == 1
select new { e.DisplayName, e.ID, e.GUID };
return sections;
}
}
错误:无法将IQueryable匿名转换为。。。ContentVw
第二个下拉列表
public IEnumerable<ContentVw> GetContent(int itemId) //itemId = first dropdown list selection
{
using (var db = my connection info)
{
var content = (from e in db.Table1 join em in db.TableToTableMaps on e.ID equals em.KnowsTableID where em.TableID == itemId select new { e.DisplayName, e.ID, e.GUID });
}
}
内容Vw:
public partial class ContentVw
{
public string Name { get; set; }
public int Id { get; set; }
public Guid GUID { get; set; }
}
控制器
public ActionResult ContentManage()
{
var _sections = new ContentService().GetSections().ToList();
ViewBag.SectionsDropdown = _sections;
return View();
}
使用:
public IEnumerable<ContentVw> GetSections()
{
using (var db = my connection info)
{
return (from e in db.Table1
join re in db.RootTables re
on e.ID equals re.Table1ID
where re.ChairID == 1
select new ContentVw { Name = e.DisplayName, // here you get ContentVw objects
Id = e.ID,
GUID = e.GUID }).ToList();
}
}
控制器:
public ActionResult ContentManage()
{
var _sections = new ContentService().GetSections();
// ViewBag.SectionsDropdown = _sections; // i prefare to pass data im model
return View(_sections);
}
视图:
@model IEnumerable<ContentVw>
@{ // populate list of <SelectListItem> for helper
var listItems = Model.Select(x => new SelectListItem {
Text = Name,
Value = Id.ToString()
}).ToList();
}
@Html.DropDownList("List", listItems)
您返回的是一个匿名对象,而不是ContentVw
。
public IEnumerable<ContentVw> GetSections()
{
using (var db = my connection info)
{
var sections = from e in db.Table1
join re in db.RootTables re
on e.ID equals re.Table1ID
where re.ChairID == 1
select new ContentVw
{
Name = e.DisplayName,
Id = e.ID,
GUID = e.GUID
};
return sections;
}
}
public IEnumerable<ContentVw> GetContent(int itemId) //itemId = first dropdown list selection
{
using (var db = my connection info)
{
var content = (from e in db.Table1
join em in db.TableToTableMaps
on e.ID equals em.KnowsTableID
where em.TableID == itemId
select new ContentVw
{
Name = e.DisplayName,
Id = e.ID,
GUID = e.GUID
});
return content;
}
}