[英]How to get a value from an Enum in a view in ASP.Net MVC4
I have little experience on ASP.Net, so I thought I'd ask. 我对ASP.Net的经验很少,所以我想问一下。
Trying to pass a value from an Enum in a create view so it can be passed to the database, but I just don't know how so I took a stab at it. 试图在创建视图中从Enum传递值,以便可以将其传递到数据库,但是我不知道该如何刺穿它。
I have a model that has a field called pageID: 我有一个名为pageID的字段的模型:
public class Article
{
public int pageID = 0;
}
public class ArticleDBContext : DbContext
{
public DbSet<Article> Articles { get; set; }
}
}
I'm trying to pass a value (int type) from an enum through the view to the database: 我正在尝试通过视图将枚举的值(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>
I know the code above is causing an error, because it isn't typed out right. 我知道上面的代码会导致错误,因为没有正确输入。
Here's my enum helper, which you probably don't need to look at: 这是我的枚举帮助器,您可能不需要看一下:
(I followed a tutorial and it is working properly) (我遵循了一个教程,它可以正常工作)
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;
}
and my enum: 和我的枚举:
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
};
Cheers 干杯
Try the Enum.GetValues() 尝试Enum.GetValues()
Example: 例:
enum Colors{ White= 0, Pink= 100, Red= 200, Black= 300};
foreach(int i in Enum.GetValues(typeof(Colors)))
Console.WriteLine(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.