今天在做项目时遇到一个问题:
开发中有些字段是枚举类型如 Dept 企业表中可能有个字段 Property 性质 0:事业单位,1:私企,2:外企,但有时我们不会单独为性质这个字段定义一张表,
而是在后台用枚举来定义此字段有可能的值,而这个时候我们在前台绑定select标签时又不好将其写死。
我首先想到的是用枚举绑定select,但一般情况下我们的枚举名都用英文表示,而将英文绑定就显得不合实际,这时候我想到的是绑定 Description 枚举描述。
下面是我的解决方案,本人小白,有更好的方法欢迎大家提出,一起加油共同进步。
一.定义枚举类 (common)
/// <summary>
/// 单位性质 0:事业单位,1:私企,2:外企
/// </summary>
public enum DeptProperty
{
[Description("事业单位")]
Institution = ,
[Description("私企")]
PrivateCompany = ,
[Description("外企")]
ForeignCompany =
}
二.获取枚举中的值和Description
ps:这块方法可能不是最好的。有更好的方法希望能提出交流。
1.Controller.cs
/// <summary>
/// 获取企业性质
/// </summary>
public JsonResult GetDeptProperty()
{
List<SelectListItem> items = new List<SelectListItem>();
//遍历枚举的公共且静态的Field,获取Field的值;
foreach (FieldInfo myEnum in typeof(Model.EnumClass.DeptProperty).GetFields(BindingFlags.Public | BindingFlags.Static))
{
items.Add(new SelectListItem()
{
Text = EnumHelper.GetDescription(myEnum),
Value = ((int)myEnum.GetValue(null)).ToString()
});
}
return Json(items, JsonRequestBehavior.AllowGet);
}
2.Helper.cs GetDescription()
/// <summary>
/// 根据Field获取Description说明的值
/// </summary>
/// <param name="fi"></param>
/// <returns></returns>
public static string GetDescription(FieldInfo fi)
{
DescriptionAttribute[] arrDesc = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return arrDesc[].Description;
}
三.前台请求数据并绑定 (js)
//加载企业性质
function getDeptProperty() {
//同步请求以免后面的操作获取不到值
$.ajaxSettings.async = false;
$.getJSON('/PracticeEnterprise/GetDeptProperty', function (data) {
$('#deptProperty').empty();
$.each(data, function (i, item) {
$('#deptProperty').append($('<option></option>').val(item.Value).text(item.Text));
});
});
}
效果:
aaarticlea/png;base64,iVBORw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