我使用Entity Framework 5创建了一个数据库,并使用了枚举功能。我现在想要使用我在下拉列表中定义的这些枚举。
我的枚举是由EF创建的:
namespace Dumpling
{
using System;
public enum DebtType : short
{
Mortgage = 0,
Installment = 1,
Revolving = 2,
Judgement = 3,
TaxLien = 4,
TradelineDispute = 5,
AddressDiscrepancy = 6,
NameVariation = 7
}
}
我希望做的是在ListView
内制作一个下拉列表。我不确定如何让下拉列表datasourceID
使用枚举。我<asp:DropDownList>
想要实现这一目标是什么意思?
答案 0 :(得分:2)
来自NopCommerce代码库,它使用MVC(稍加修改):
public static SelectList ToSelectList<TEnum>(this TEnum enumObj, bool markCurrentAsSelected = true) where TEnum : struct {
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
select new { ID = Convert.ToInt32(enumValue), Name = enumValue.ToString() };
object selectedValue = null;
if (markCurrentAsSelected)
selectedValue = Convert.ToInt32(enumObj);
return new SelectList(values, "ID", "Name", selectedValue);
}
没有通过微小的修改来测试这个以删除一些特定于NC的代码,但基本概念应该让你到那里。当然你不会有SelectList,但你应该可以很容易地修改它。
答案 1 :(得分:0)
好吧,如果你在ListView中有你的DropDownList,那么我会使用以下方法(它可能会被优化,我的ASP.NET Web Forms技能正在生锈)。
型号:
public enum AnimalType
{
Dog = 1,
Cat = 2,
Sheep = 3,
Horse = 4
}
public class Animal
{
public string Name { get; set; }
public AnimalType Type { get; set; }
}
页:
<asp:ListView ID="lstAnimals" runat="server" onitemdatabound="lstAnimals_ItemDataBound">
<ItemTemplate>
<div>
<asp:TextBox runat="server" Text='<%#Eval("Name") %>' />
<asp:DropDownList ID="lstAnimalType" runat="server" DataValueField="Id" DataTextField="Description" />
</div>
</ItemTemplate>
代码背后:
protected void Page_Load(object sender, EventArgs e)
{
var animals = new List<Animal>();
animals.Add(new Animal() { Name = "Doggie", Type = AnimalType.Dog});
animals.Add(new Animal() { Name = "Sheepie", Type = AnimalType.Sheep });
lstAnimals.DataSource = animals;
lstAnimals.DataBind();
}
protected void lstAnimals_ItemDataBound(object sender, ListViewItemEventArgs e)
{
var ddlAnimalType = (DropDownList)e.Item.FindControl("lstAnimalType");
var enumValues = Enum.GetValues(typeof (AnimalType)).Cast<AnimalType>().ToList();
var bindableList = enumValues.Select(v => new { Id = (int) v, Description = v.ToString() });
ddlAnimalType.DataSource = bindableList;
ddlAnimalType.DataBind();
}