![](/img/trans.png)
[英]ASP.net MVC : Create MVC 5 Application using EF6 with Code First and Existing Database
[英]ASP.Net MVC Filter data using dropdownfield from Enum field EF6
我使用ASP.Net 4.5 MVC EF6实体框架
我的模型中有一个Enum。 我喜欢按枚举类型字段的where子句对列表进行过滤/排序。为此,我构建了一个DroppDownField。 我的选择清单:
var FGenre = Enum.GetValues(typeof(FileGenre)).Cast<FileGenre>().Select(c => new SelectListItem{ Text = c.ToString(), Value= c.ToString() });
所以我得到一个列表(值和文本是枚举中的文本)。
现在,我想用“哪里”过滤数据:
var model = db.Filetypes.Where(fg => fg.FileGenres.Equals(????????).);
我如何建立一个枚举要过滤的子句
要么
一般来说,我还是LINQ,Lambda和MVC的新手。 如果有人有办法改善此代码,请随时添加您的意见。
编辑:我的模型:
public partial class Filetype
{
[Display(Name = "ID")]
public int FiletypeId { get; set; }
[StringLength(128)]
[Display(Name="Datei Art")]
public string TypeName { get; set; }
[Display(Name = "Genre")]
public FileGenre FileGenres { get; set; }
.......
public virtual ICollection<FiletypeRole> FiletypeRoles { get; set; }
}
public enum FileGenre
{
NNB_A,
NNB_B,
NNB_C
}
问题是选择列表将枚举表示为字符串,因此您必须将其转换为查询中的枚举,这很丑陋:
FileGenre MyGenre = (FileGenre) Enum.Parse(typeof(FileGenre), model.FileGenre, true);
因此,可以将枚举与int值一起使用。 像这样声明:
public enum FileGenre
{
NNB_A = 1,
NNB_B = 2,
NNB_C = 3
}
并填充选择列表(在这里,我创建了一个返回选择列表的方法):
public SelectList GetAsSelectList()
{
var enumList = (from Enum e in Enum.GetValues(typeof(FileGenre))
select new
{
Name = e,
Id = Convert.ToInt32(e).ToString()
}).ToList();
return new SelectList((IEnumerable)enumList, "Id", "Name");
}
现在,选择列表将具有一个int
值,并且在您将其发布并在过滤中使用它时将正确绑定:
var model = db.Filetypes.Where(fg => fg.FileGenres == model.FileGenre).ToList();
如@Alberto所述, Filetype
的FileGenre
属性应为单数,因为FileGenres
使其看起来像是一个集合或列表,这可能会造成混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.