【发布时间】:2014-12-27 10:22:32
【问题描述】:
我在我的 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 是多层的,我在领域层有模型,而视图扩展是作为视图的项目。
我的问题是为什么我无法解析页面浏览扩展方法?
非常感谢您的建议。
【问题讨论】:
-
GetDropDownListItems方法需要 2 个参数bool?, bool但您传递了三个string, bool?, bool。 -
你是对的斯蒂芬,我发布了错误的方法。我用有关视图扩展方法的更多详细信息更新了问题。
-
报错信息还是一样吗? (它没有任何意义)。我的问题是这一切到底应该做什么,
@Html.ExDropDownList()是什么?似乎这一切都可以通过使用 MVC 的内置方法的几行代码来完成 -
报错信息不一样。 @html.ExDropDownList() 是我正在使用的 html 助手。最初的项目是在 2010 年使用 linq-to-sql 开发的;现在我使用的是 EF 6.1。我想我会更容易更新它而不是重写整个程序。我在很多视图中使用这些方法;我也必须保持相同的数据库结构。
标签: c# asp.net asp.net-mvc extension-methods selectlistitem