如何在MVC3中绑定enum值以选择正确的enum值?

本文关键字:enum 选择 MVC3 绑定 | 更新日期: 2023-09-27 18:06:18

我想这一定是一个已知的问题,我只是还没有找到正确的答案。

我有一个类似这样的enum

public enum CardType
{
    [Description( "" )]
    None = 0,
    Visa = 1,
    Mastercard = 2,
    Discover = 3,
    [Description( "American Express" )]
    AmericanExpress = 4
}

现在,正确的术语应该是这样的,这是从数据库中的一个表中提取的,因为我只得到我现在启用的某些卡片类型。我们只有Visa/Mastercard

<select name="CardType" id="CardType">
    <option value="1">Visa</option>
    <option value="2">Mastercard</option>
</select>

现在假设我想默认选择万事达卡。我必须这样做

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"而不是传递的数字值…我对如何解决这个问题感到困惑……只有几个解决方案,我不想使用,如果我能帮助它,因为它只意味着更多的工作…

如何在MVC3中绑定enum值以选择正确的enum值?

我有点困惑你在做什么,我真的不明白。

 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);

直接在你的组合框中使用卡片?