Tôi đã sử dụng các mục sau trong MVC3 (aspx) .NETFramework 4.0 của tôi hoạt động rất tốt.SelectListItem/cập nhật mẫu đơn MVC3 4.0 lên MVC5 4.5.1/xem phương pháp mở rộng
xem phương pháp khuyến nông trang:
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;
}
phần mô hình:
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);
}
}
Trong giao diện:
@Html.ExDropDownList("DoYouSmokeNowID", this.GetDropDownListItems("DoYouSmokeNowValues", this.Model.PersonalSocial.DoYouSmokeNowID, false), this.isReadOnly)
Khi tôi cập nhật các ứng dụng để MVC5 .NETFramework 4.5.1. Đầu tiên tôi không thể giải quyết GetDropDownListItems, vì vậy tôi đã sao chép nó từ mô hình mở rộng sang chế độ xem bằng cách sử dụng @functions, tôi nhận được lỗi này.
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.
Một điều khác, giải pháp MVC3 là một dự án, trong khi MVC5 là đa lớp và tôi có các mô hình trong lớp Domain, trong khi tiện ích xem là dự án như các quan điểm.
Câu hỏi của tôi là lý do tại sao tôi không thể giải quyết phương pháp tiện ích chế độ xem trang?
Sẽ đánh giá cao đề xuất của bạn.
'phương pháp GetDropDownListItems' hy vọng 2 thông số' bool ?, bool 'nhưng bạn truyền ba chuỗi', bool ?, bool'. –
Bạn đúng Stephen, tôi đã đăng sai phương pháp. Tôi đã cập nhật câu hỏi với nhiều chi tiết hơn về phương pháp tiện ích chế độ xem. – hncl
Thông báo lỗi có giống nhau không? (nó chả có nghĩa gì cả). Câu hỏi của tôi là tất cả điều này được cho là đang làm gì, và cái gì '@ Html.ExDropDownList()'? Có vẻ như tất cả điều này có thể được thực hiện chỉ trong một vài dòng mã sử dụng phương thức tích hợp của MVC –