I used the following in my MVC3 (aspx) .NETFramework 4.0 works great.
view 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 the view:
@Html.ExDropDownList("DoYouSmokeNowID", this.GetDropDownListItems("DoYouSmokeNowValues", this.Model.PersonalSocial.DoYouSmokeNowID, false), this.isReadOnly)
When I updated the application to MVC5 .NETFramework 4.5.1. 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.
One other thing, the MVC3 solution was one project, while MVC5 is multi layer and I have the models in the Domain layer, while the view extension is the project as the views.
My question is why I can't resolve the page view extension method?
Would appreciate your suggestions.
ViewPage
is a base class for WebForms-style views (http://msdn.microsoft.com/en-us/library/system.web.mvc.viewpage%28v=vs.118%29.aspx).
Razor views use a different class, WebViewPage
(http://msdn.microsoft.com/en-us/library/gg402107%28v=vs.118%29.aspx).
So, without actually trying to recreate your helpers, I would guess that at a minimum you need to hang the extension method off of WebViewPage:
GetDropDownListItems<T>(this WebViewPage<T> viewPage, string listName, int? currentValue, bool addBlank)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With