[英]Get Enum value to show on Dropdownlist Asp.Net MVC
我有一個這樣的枚舉:
public enum PaymentType
{
Self=1,
Insurer=2,
PrivateCompany=3
}
我將其顯示為Controller內部的選擇框選項:
List<Patient.PaymentType> paymentTypeList =
Enum.GetValues(typeof (Patient.PaymentType)).Cast<Patient.PaymentType>().ToList();
ViewBag.PaymentType = new SelectList(paymentTypeList);
在這里,我看到只有枚舉的字符串部分(例如“ Self”)進入前端,因此在下拉列表中我不會得到枚舉的值(例如“ 1”)。 如何傳遞文本以及枚舉值來選擇列表?
您可以編寫如下擴展方法:
public static System.Web.Mvc.SelectList ToSelectList<TEnum>(this TEnum obj)
where TEnum : struct, IComparable, IFormattable, IConvertible // correct one
{
return new SelectList(Enum.GetValues(typeof(TEnum)).OfType<Enum>()
.Select(x =>
new SelectListItem
{
Text = Enum.GetName(typeof(TEnum), x),
Value = (Convert.ToInt32(x)).ToString()
}), "Value", "Text");
}
並在操作中像這樣使用它:
public ActionResult Test()
{
ViewBag.EnumList = PaymentType.Self.ToSelectList();
return View();
}
並在視圖中:
@Html.DropDownListFor(m=>m.SomeProperty,ViewBag.EnumList as SelectList)
<select id="EnumDropDown" name="EnumDropDown">
<option value="1">Self</option>
<option value="2">Insurer</option>
<option value="3">PrivateCompany</option>
</select>
public enum PaymentType
{
Self=1,
Insurer=2,
PrivateCompany=3
}
獲得自我價值:
int enumNumber = (int)PaymentType.Self; //enumNumber = 1
例:
getEnum(PaymentType.Self);
private void getEnum(PaymentType t)
{
string enumName = t.ToString();
int enumNumber = (int)t;
MessageBox.Show(enumName + ": " + enumNumber.ToString());
}
MVC5中有一個擴展方法,稱為SelectExtensions.EnumDropDownListFor ,它將為您生成下拉列表,並將響應綁定回模型中的enum屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.