In ASP.NET MVC3 I think it has got to be a known problem, and I just haven't found the correct answer to my problem.
I have an enum something like this
public enum CardType
{
[Description( "" )]
None = 0,
Visa = 1,
Mastercard = 2,
Discover = 3,
[Description( "Americ开发者_JAVA技巧an Express" )]
AmericanExpress = 4
}
Now the correct term would to be something like this which is being pulled from a table in the database, because I only get certain card types that I have enabled right now. Which we only have Visa/Mastercard
<select name="CardType" id="CardType">
<option value="1">Visa</option>
<option value="2">Mastercard</option>
</select>
Now lets say I want Mastercard to be defaulted selected. I have to do something like this
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 );
Now I don't have a problem with this part, which is not always not promising to work. Sometimes it will pass "Mastercard" instead of the number value passed... I am confused on how to fix this... Only a few solutions which I don't want to use if I can help it because it just means more work...
I'm kinda confused what you are doing with this, I don't really understand.
Selected = (d.ID == (int)CardType)
You get the ID and check it against the Enum CardType? Doesn't this give the following error:
CardType' is a 'type' but is used like a 'variable'
Shouldn't this work?
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);
And use the oCards directly into your combobox?
精彩评论