我有一個可以爲空的枚舉,不像其他人在同一頁上,不起作用。我有一個枚舉,Title
,從而使用擴展方法將有助於填充頁面上的下拉列表。這裏的ViewBag聲明看起來是這樣的:在ToSelectList擴展方法下拉不起作用
ViewBag.TitleList = EnumExtensions.ToSelectList<Title>("[select]");
現在,也許有人可以解釋給我,但是這是魔法發生,當談到在MVC約束力。如果在調用if(ModelState.IsValid)
時該頁面無效,則在重新渲染屏幕時,再次調用上述語句。但是這一次,正確的下拉選項將被選中(取決於您當時選擇了哪一個)。
進一步挖掘,這是方法聲明:
public static SelectList ToSelectList<TEnum>(string nullEntry = null) where TEnum : struct
{
return ToSelectList<TEnum>(nullEntry, null);
}
public static SelectList ToSelectList<TEnum>(string nullEntry = null, string selectedValue = null) where TEnum : struct
{
var enumType = typeof(TEnum);
var values = Enum.GetValues(enumType).OfType<TEnum>();
List<SelectListItem> items = ToSelectList<TEnum>(values, nullEntry, selectedValue);
SelectList sl = new SelectList(items, "Value", "Text", selectedValue);
return sl;
}
public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, string nullEntry, string selectedValue = null)
{
List<SelectListItem> items;
if ((typeof(T).IsEnum))
{
items = enumerable.Select(f => new SelectListItem()
{
Text = f.GetDescription(),
Value = f.ToString(),
Selected = f.ToString() == selectedValue
}).ToList();
}
else
{
items = enumerable.Select(f => new SelectListItem()
{
Text = f.ToString(),
Value = f.ToString()
}).ToList();
}
if (!string.IsNullOrEmpty(nullEntry))
{
items.Insert(0, new SelectListItem() { Text = nullEntry, Value = "" });
}
return items;
}
只是有一些重載處理隨機的情況下,雖然想必其中的一些將不再需要。
正如我所說,正確的項目將被選爲其他枚舉,但對於這個特定的標題,它不會。這裏的枚舉聲明:
public enum Title
{
Mr,
Miss,
Mrs,
Ms
}
最後,使用頁面本身DropDownListFor
的聲明;
@Html.DropDownListFor(x => x.Title, (SelectList)ViewBag.TitleList)
的問題是,當我第一次訪問該頁面時,選擇的項目總是「[選擇]」(當提供枚舉值模型爲null)。但是,模型屬性Title
肯定的值已設置,並且SelectedItem
屬性也設置爲下拉列表,但在屏幕上,它默認爲「[select]」,這是意外的。
任何想法?
我從你的問題不明白什麼是不工作。 –
我有這樣做的習慣,對不起!修改了最後一段。 – Kezzer
您能否顯示爲此視圖提供服務的控制器操作? –