我对ASP.Net没什么经验,所以我想我会问。
尝试在创建视图中传递Enum中的值,以便将其传递给数据库,但我只是不知道如何对它进行了尝试。
我的模型有一个名为pageID的字段:
public class Article
{
public int pageID = 0;
}
public class ArticleDBContext : DbContext
{
public DbSet<Article> Articles { get; set; }
}
}
我正在尝试将枚举值(int类型)从视图传递到数据库:
<tr>
<td>
<h2>Select Page for Insert</h2>
</td>
</tr>
<tr>
<td>
@Html.DropDownListFor(model => model.pageID.Equals(EnumHelper.GetSelectedItemList<PageIndex>().SelectedValue))
</td>
</tr>
</table>
<p>
<input id="createButton" type="submit" value="Create" />
</p>
</fieldset>
我知道上面的代码导致错误,因为它没有正确输出。
这是我的枚举助手,您可能不需要查看:
(我按照教程进行了操作)
public static SelectList GetSelectedItemList<T>() where T : struct
{
T t = default(T);
if (!t.GetType().IsEnum) { throw new ArgumentNullException("Please make sure that T is of Enum Type"); }
var nameList = t.GetType().GetEnumNames();
int counter = 0;
Dictionary<int, String> myDictionary = new Dictionary<int, string>();
if (nameList != null && nameList.Length > 0)
{
foreach (var name in nameList)
{
T newEnum = (T) Enum.Parse(t.GetType(), name);
string description = getDescriptionFromEnumValue(newEnum as Enum);
if (!myDictionary.ContainsKey(counter))
{
myDictionary.Add(counter, description);
}
counter++;
}
counter = 0;
return new SelectList(myDictionary, "Key", "Value");
}
return null;
}
private static string getDescriptionFromEnumValue(Enum value)
{
DescriptionAttribute descriptionAttribute =
value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return descriptionAttribute == null ?
value.ToString() : descriptionAttribute.Description;
}
和我的枚举:
public enum PageIndex : int
{
[Description("Developmental Disabilities Tip Sheet")]
ddTipSheets = 1,
[Description("Hiiiiiiiiiiiiiiiiiiii")]
Example1 = 2,
[Description("I don't know what I'm doing")]
Example2 = 3
};
干杯
答案 0 :(得分:0)
尝试使用Enum.GetValues()
示例:
enum Colors{ White= 0, Pink= 100, Red= 200, Black= 300};
foreach(int i in Enum.GetValues(typeof(Colors)))
Console.WriteLine(i);