5

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はマルチレイヤーであり、ドメインレイヤーにモデルがあり、ビュー拡張はビューとしてのプロジェクトです。

私の質問は、ページ ビュー拡張メソッドを解決できないのはなぜですか?

あなたの提案をいただければ幸いです。

4

1 に答える 1

6

ViewPageWebFormsスタイル ビュー ( http://msdn.microsoft.com/en-us/library/system.web.mvc.viewpage%28v=vs.118%29.aspx )の基本クラスです。

Razorビューは別のクラスを使用しますWebViewPage( http://msdn.microsoft.com/en-us/library/gg402107%28v=vs.118%29.aspx )。

したがって、実際にヘルパーを再作成しようとせずに、少なくとも WebViewPage から拡張メソッドをハングアップする必要があると思います。

GetDropDownListItems<T>(this WebViewPage<T> viewPage, string listName, int? currentValue, bool addBlank)
于 2014-11-02T08:03:06.100 に答える