From an int:
YourEnum foo = (YourEnum)yourInt;
From a string:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// The foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
}
Update:
From number you can also
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
For MVC v5.1 use Html.EnumDropDownListFor
@Html.EnumDropDownListFor(
x => x.YourEnumField,
"Select My Type",
new { @class = "form-control" })
For MVC v5 use EnumHelper
@Html.DropDownList("MyType",
EnumHelper.GetSelectList(typeof(MyType)) ,
"Select My Type",
new { @class = "form-control" })
For MVC 5 and lower
I rolled Rune's answer into an extension method:
namespace MyApp.Common
{
public static class MyExtensions{
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
}
}
This allows you to write:
ViewData["taskStatus"] = task.Status.ToSelectList();
by using MyApp.Common
Best Answer
I had this problem 8 years ago, but with ASP as we called it then
The problem is that the ASP code runs on a remote server, whereas your smartcard reader is a local piece of hardware
How I got round it was a small client application that regularly polled the smartcard reader for a card insert/removal. If a card was inserted, then it called a web-service to alert the server, which created a unique key based on the card and some random number. It then asked the user to enter a PIN, which was related to the card id and random number.
This meant that it required the particular card and an unreapeatable number. I pretty sure I used SSL to encrypt the web-service message, which of course is the most vulnerable part of the system
that's how I did it. The SCM tech support guys are really helpful and speak excellent English, it may be worth giving them a shout