SelectListItem /更新应用程序表单MVC3 4.0到MVC5 4.5.1 /视图扩展方法

时间:2014-10-31 06:45:04

标签: c# asp.net asp.net-mvc extension-methods selectlistitem

我在我的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.

另一件事,MVC3解决方案是一个项目,而MVC5是多层的,我在域层中有模型,而视图扩展是项目作为视图。

我的问题是为什么我无法解析页面视图扩展方法?

非常感谢您的建议。

1 个答案:

答案 0 :(得分:6)

ViewPage WebForms 样式视图(http://msdn.microsoft.com/en-us/library/system.web.mvc.viewpage%28v=vs.118%29.aspx)的基类。

Razor 视图使用其他类WebViewPagehttp://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)
相关问题