我正在尝试以用户友好的可读名称使用枚举 但我无法找到如何将它绑定到我的视图
这是我到目前为止所做的:
public enum MyDayOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
SunTilFir = 7,
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public int Hour { get; set; }
public MyDayOfWeek Days { get; set; }
}
public static class ChangeEnumName
{
public static string EnumValue(this MyDayOfWeek e)
{
switch (e)
{
case MyDayOfWeek.SunTilFir:
return "Sunday until Friday ";
}
return "Horrible Failure!!";
}
}
如何将ChangeEnum名称绑定到我的视图?
答案 0 :(得分:2)
您可以做的是在模型上创建只读属性,从中返回您的FriendlyName
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public int Hour { get; set; }
public MyDayOfWeek Days { get; set; }
public string DaysFriendlyName
{
get
{
switch(this.Days)
{
case MyDayOfWeek.SunTilFir:
return "Sunday until Friday ";
}
return "Horrible Failure!!";
}
}
}
可能更好的是不在您的只读属性的主体中实现切换,但可能为它做一个扩展方法?所以你的身体会是这样的:
public string DaysFriendlyName
{
get
{
return this.Days.ToFriendlyName();
}
}
扩展方法:
namespace UniPro.Models
{
public static class DaysEnumExtensions
{
public static string ToFriendlyName(this MyDayOfWeek days)
{
switch (days)
{
//....
}
}
}
}
扩展方法的好处在于你可以松开readonly属性并直接从你的剃刀视图绑定到扩展方法(在你的剃刀视图中使用'为此设置为工作)。
答案 1 :(得分:1)
您可以尝试这样做:
public enum MyDayOfWeek
{
[UserFriendlyName("Sunday")]
Sunday = 0,
[UserFriendlyName("Monday")]
Monday = 1,
[UserFriendlyName("Tuesday")]
Tuesday = 2,
[UserFriendlyName("Wednesday")]
Wednesday = 3,
[UserFriendlyName("Thursday")]
Thursday = 4,
[UserFriendlyName("Friday")]
Friday = 5,
[UserFriendlyName("Saturday")]
Saturday = 6,
[UserFriendlyName("Sunday until Friday")]
SunTilFir = 7
}
public class UserFriendlyNameAttribute : Attribute
{
public string Text { get; set; }
public UserFriendlyNameAttribute(string text)
{
Text = text;
}
}
public static class EnumExtensions
{
public static string GetUserFriendlyName(this MyDayOfWeek myDayOfWeek)
{
return GetUserFriendlyNameAttributeText(typeof(MyDayOfWeek), myDayOfWeek.ToString());
}
private static string GetUserFriendlyNameAttributeText(this Type type, string memberName)
{
var memInfo = type.GetMember(memberName);
if (memInfo.Length == 0)
return string.Empty;
var attributes = memInfo[0].GetCustomAttributes(typeof(UserFriendlyNameAttribute), false);
if (attributes.Length == 0)
return null;
return ((UserFriendlyNameAttribute) attributes[0]).Text;
}
}
因此,您可以在视图中将其用作扩展方法:
MyDayOfWeek.SunTilFir.GetUserFriendlyName()