![](/img/trans.png)
[英]I want a generic method to take an enum and creates a list of type objects from the enum setting ID and Name properites
[英]Enum to List<Object> (Id, Name)
將enum
轉換為 Id/Name 對象列表的最佳實踐是什么?
Enum
:
public enum Type
{
Type1= 1,
Type2= 2,
Type3= 3,
Type4= 4
}
Object
:
public class TypeViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
類似的東西:
var typeList = new List<TypeViewModel>();
foreach (Type type in Enum.GetValues(typeof(Type)))
{
typeList.Add(new TypeViewModel(type.Id, type.Name));
}
使用LINQ :
var typeList = Enum.GetValues(typeof(Type))
.Cast<Type>()
.Select(t => new TypeViewModel
{
Id = ((int)t),
Name = t.ToString()
});
結果:
假設我們有:
public enum Gender
{
Male = 0,
Female = 1
}
和模型:
public class Person
{
public int Id {get; set;}
public string FullName {get; set;}
public Gender Gender {get; set;}
}
鑒於您可以簡單地使用:
@model YourNameSpaceWhereModelsAre.Person;
...
@Html.BeginForm(...)
{
@Html.HiddenFor(model => model.Id);
@Html.EditorFor(model => model.FullName);
@Html.EnumDropDownListFor(m => Model.Gender);
<input type="submit"/>
}
您可以找到更多信息或MSDN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.