を私はまだ勉強していますが、私は私が働いているため、同様の問題がありました溶液。 My Categoryは列挙型で、Selectタグの内容を決定する列挙型を調べるテンプレートコントロールを使用します。
としてそれがビューで使用されます。
public enum Category
{
[Description("Operative")]
Operative=1,
[Description("Non Operative")]
NonOperative=2,
[Description("Therapeutic")]
Therapeutic=3
}
private Category _CategoryCode;
public Category CategoryCode
{
get { return _CategoryCode; }
set { _CategoryCode = value; }
}
SelectListForEnumの構造:カテゴリーの列挙は説明が飾られ
<%= Html.DropDownList
(
"CategoryCode",
MvcApplication1.Utility.EditorTemplates.SelectListForEnum(typeof(WebSite.ViewData.Episode.Procedure.Category), selectedItem)
) %>
は、選択項目のテキスト値として使用される属性次のように、列挙型定義および現在選択されている項目の索引を使用して選択項目のリストを返します。
public static SelectListItem[] SelectListForEnum(System.Type typeOfEnum, int selectedItem)
{
var enumValues = typeOfEnum.GetEnumValues();
var enumNames = typeOfEnum.GetEnumNames();
var count = enumNames.Length;
var enumDescriptions = new string[count];
int i = 0;
foreach (var item in enumValues)
{
var name = enumNames[i].Trim();
var fieldInfo = item.GetType().GetField(name);
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
enumDescriptions[i] = (attributes.Length > 0) ? attributes[0].Description : name;
i++;
}
var list = new SelectListItem[count];
for (int index = 0; index < list.Length; index++)
{
list[index] = new SelectListItem { Value = enumNames[index], Text = enumDescriptions[index], Selected = (index == (selectedItem - 1)) };
}
return list;
}
最終的にDDLがうまく表示されます。
これが役に立ちます。これを行うためのよりよい方法についてのコメントは非常に高く評価されます。
優れた記事は当然のことながら、これは理にかなっているが、私は助けるが、カスタムモデルを置くViewModelには、カスタムのViewModel内のオブジェクトのプロパティ名を前置するフォームのフィールド名を引き起こすことに気づくことができませんでした。これは問題ではありませんが、モデルを更新するためのもう1つのステップが追加されます。私はおそらく不必要に泣いていますか? –