C# 如何绑定MVC3中的枚举值以选择正确的值?
在ASP.NETMVC3中,我认为这一定是一个已知的问题,我只是没有找到问题的正确答案 我有一个类似这样的枚举C# 如何绑定MVC3中的枚举值以选择正确的值?,c#,.net,asp.net-mvc-3,.net-4.0,C#,.net,Asp.net Mvc 3,.net 4.0,在ASP.NETMVC3中,我认为这一定是一个已知的问题,我只是没有找到问题的正确答案 我有一个类似这样的枚举 public enum CardType { [Description( "" )] None = 0, Visa = 1, Mastercard = 2, Discover = 3, [Description( "American Express" )] AmericanExpress = 4 } CardTypes
public enum CardType
{
[Description( "" )]
None = 0,
Visa = 1,
Mastercard = 2,
Discover = 3,
[Description( "American Express" )]
AmericanExpress = 4
}
CardTypes = new List<SelectListItem>();
var ctypes = db.ExecuteReaderDynamic( "CardType_GetAll", null, System.Data.CommandType.StoredProcedure )
.Select( d =>
new SelectListItem
{
Text = d.Name,
Value = d.ID.ToString()
Selected = (d.ID == (int)CardType)
} );
CardTypes.AddRange( ctypes );
现在正确的术语应该是这样的,它是从数据库中的一个表中提取的,因为我现在只得到我已经启用的某些卡类型。我们只有Visa/Mastercard
<select name="CardType" id="CardType">
<option value="1">Visa</option>
<option value="2">Mastercard</option>
</select>
现在让我们假设我希望万事达卡被默认选中。我必须这样做
public enum CardType
{
[Description( "" )]
None = 0,
Visa = 1,
Mastercard = 2,
Discover = 3,
[Description( "American Express" )]
AmericanExpress = 4
}
CardTypes = new List<SelectListItem>();
var ctypes = db.ExecuteReaderDynamic( "CardType_GetAll", null, System.Data.CommandType.StoredProcedure )
.Select( d =>
new SelectListItem
{
Text = d.Name,
Value = d.ID.ToString()
Selected = (d.ID == (int)CardType)
} );
CardTypes.AddRange( ctypes );
现在我对这个部分没有任何问题,它并不总是不可能工作。有时它会传递Mastercard而不是传递的数字值。。。我不知道如何解决这个问题。。。只有一些解决方案我不想使用,如果我可以帮助它,因为这意味着更多的工作…我有点困惑你在做什么,我真的不明白
Selected = (d.ID == (int)CardType)
获取ID并对照Enum CardType进行检查?这不会导致以下错误:
CardType' is a 'type' but is used like a 'variable'
这不管用吗
CardTypes = new List<SelectListItem>();
var ctypes = db.ExecuteReaderDynamic( "CardType_GetAll", null, System.Data.CommandType.StoredProcedure )
.Select( d =>
new SelectListItem
{
Text = d.Name,
Value = d.ID.ToString()
Selected = false
} );
CardTypes.AddRange( ctypes );
SelectList oCards = new SelectList(oCardTypes, (int)CardType.Mastercard);
然后直接在组合框中使用cards?表中没有CardType属性,我只是将其转换为整数。例如,将其设置为数据库中ID为2的Mastercard的问题。。。它不会选择它选择第一个,因为它是选择列表中的第一个选项。如果我通过HttpPost或其他方式提交数据,它将根据设置值。这是融合,因为它应该工作。哦,更不用说当前选择下拉列表代码的工作方式是,它试图设置所选的值。基本上,它不使用我所做的选择列表,甚至做新的选择列表等都不起作用,因为它期望像MasterCard这样的值,而不是2,所以理论上2==MasterCard是假的。。。这就是问题所在,我开始认为我必须克隆Select Internal以更好地处理比较,它首先比较Enum.ToString,如果失败,它将尝试比较数值比较……那么将所有Select值填入False default有什么错?ID与枚举索引匹配是吗?因此,当您在选择列表中选择正确的一个时,这应该可以正常工作?你为什么要用ToString?您完全可以将Int值推入SelectListItem值。