【发布时间】:2016-01-06 16:01:29
【问题描述】:
我正在填写一个表单,但是当从下拉列表中选择一个选项并单击提交时,无论我选择什么选项,它总是会解析顶部的选项。显示的值永远不会改变,因此您将其保留为默认选项“请选择...”并单击提交,这将保持为“请选择...”,但数据库中的条目始终是出现在下拉列表的顶部。
这是模型:
public enum Medium
{
[Description("Teleconference & Report")]
Teleconference_Report,
[Description("Email & Telephone")]
Email_Telephone
}
[Required]
[Display(Name = "Medium")]
public Medium Medium { get; set; }
这是表单中的字段:
<div class="form-group">
@Html.LabelFor(model => model.Medium, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.DropDownList("MediumID", null, "Please select...", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Medium, "", new { @class = "text-danger" })
</div>
</div>
“MediumID”DropDownList 使用 viewbag 填充,该 viewbag 设置为以下返回值:
// Puts all of the mediums of communication into a user friendly dropdownlist.
public List<SelectListItem> GetMediumList()
{
List<SelectListItem> mediumList = new List<SelectListItem>();
foreach (Medium state in EnumToList<Medium>())
{
mediumList.Add(new SelectListItem
{
Text = GetEnumDescription(state),
Value = state.ToString(),
});
}
return mediumList;
}
下面显示了另一个名为“频率”的枚举的表单部分,但这些没有更改为用户友好的字符串(并且工作正常)。
<div class="form-group">
@Html.LabelFor(model => model.Frequency, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.EnumDropDownListFor(model => model.Frequency, "Please select...", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Frequency, "", new { @class = "text-danger" })
</div>
</div>
下面,显示了将枚举转换为用户友好字符串的两种方法:
// Returns a 'user friendly', readable version of the enum.
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
// Puts all of the same enums into a list.
public static IEnumerable<T> EnumToList<T>()
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this.
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
最后,这是绑定/绑定字段的方法签名:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Point,ApplicationID,MediumID,Frequency,StartDate,EndDate")] TouchPoint touchPoint)
在此方法中,下拉菜单使用以下内容传递给视图:
ViewBag.MediumID = GetMediumList();
非常感谢任何帮助。
【问题讨论】:
标签: asp.net-mvc forms enums html-helper viewbag