我正在填寫表格,但是從下拉列表中選擇一個選項並單擊提交時,無論我選擇什麼選項,它都會解析第一個通過。顯示的值永遠不會改變,所以它將它作爲默認選項'請選擇...'並單擊提交,這會保留爲'請選擇...',但數據庫中的條目總是出現在下降的頂部。Html Helper下拉列表在提交/數據庫中將值切換到頂部選項
下面是該模型:
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填充:
// 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();
任何幫助,非常感謝。