I used the following in my MVC3 (aspx) .NETFramework 4.0 works fine.
view the page extension method:
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; }
Partial Model:
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); } }
In view:
@Html.ExDropDownList("DoYouSmokeNowID", this.GetDropDownListItems("DoYouSmokeNowValues", this.Model.PersonalSocial.DoYouSmokeNowID, false), this.isReadOnly)
When I upgraded the application to MVC5.NETFramework 4.5.1. At first I could not resolve GetDropDownListItems, so I copied it from the extension model to the view using @functions, I get this error.
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.
Another thing, the MVC3 solution was one project, and MVC5 was multi-level, and I have models at the domain level, and the extension of the view is the project as views.
My question is why I canβt resolve the page view extension method?
Thank you for your suggestions.