I have little experience on ASP.Net, so I thought I'd ask.
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.
I have a model that has a field called 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:
<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()
Example:
enum Colors{ White= 0, Pink= 100, Red= 200, Black= 300};
foreach(int i in Enum.GetValues(typeof(Colors)))
Console.WriteLine(i);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.