MVC3 (aspx) .NETFramework 4.0 で以下を使用しました。
ビューページ拡張メソッド:
public static List<SelectListItem> GetDropDownListItems<T>(this ViewPage<T> viewPage, string listName, int? currentValue, bool addBlank)
where T : class
{
List<SelectListItem> list = new List<SelectListItem>();
IEnumerable<KeyValuePair<int, string>> pairs = viewPage.ViewData[listName] as IEnumerable<KeyValuePair<int, string>>;
if (addBlank)
{
SelectListItem emptyItem = new SelectListItem();
list.Add(emptyItem);
}
foreach (KeyValuePair<int, string> pair in pairs)
{
SelectListItem item = new SelectListItem();
item.Text = pair.Value;
item.Value = pair.Key.ToString();
item.Selected = pair.Key == currentValue;
list.Add(item);
}
return list;
}
部分モデル:
public static Dictionary<int, string> DoYouSmokeNowValues = new Dictionary<int, string>()
{
{ 1, "Yes" },
{ 2, "No" },
{ 3, "Never" }
};
public static int MapDoYouSmokeNowValue (string value)
{
return (from v in DoYouSmokeNowValues
where v.Value == value
select v.Key).FirstOrDefault();
}
public static string MapDoYouSmokeNowValue (int? value)
{
return (from v in DoYouSmokeNowValues
where v.Key == value
select v.Value).FirstOrDefault();
}
public string DoYouSmokeNow
{
get
{
return MapDoYouSmokeNowValue(DoYouSmokeNowID);
}
set
{
DoYouSmokeNowID = MapDoYouSmokeNowValue(value);
}
}
ビューで:
@Html.ExDropDownList("DoYouSmokeNowID", this.GetDropDownListItems("DoYouSmokeNowValues", this.Model.PersonalSocial.DoYouSmokeNowID, false), this.isReadOnly)
アプリケーションを MVC5 .NETFramework 4.5.1 に更新したとき。最初に GetDropDownListItems を解決できなかったので、@functions を使用して拡張モデルからビューにコピーしたところ、このエラーが発生しました。
The type argument for method 'IEnumerable<SelectedItem> ASP._Page_Views_Visit_PhysicalExam_cshtml.GetDropDownListItems<T>(ViewPage<T>, string,,int?,bool)' cannot be inferred from the usage. Try specifying the the type arguments explicity.
もう1つ、MVC3ソリューションは1つのプロジェクトでしたが、MVC5はマルチレイヤーであり、ドメインレイヤーにモデルがあり、ビュー拡張はビューとしてのプロジェクトです。
私の質問は、ページ ビュー拡張メソッドを解決できないのはなぜですか?
あなたの提案をいただければ幸いです。