我正在开发一个MVC应用程序。在我的应用程序中,我需要按洲洲创建一个下拉列表组。像
等
在创建了一个包含大陆的单个表中,国家/地区只保持它们之间的父子关系。
所以我的模型就像:
public partial class String
{
public int IID { get; set; }
public string Name { get; set; }
public Nullable<int> ParentId { get; set; }
public int IType { get; set; }
}
这里parentId是大陆的空值,而国家/地区的大陆ID(IID是PK)是父ID。
我的控制器就像
public ActionResult Create()
{
var ContinentList = db.Strings.Where(c => c.IType == 1).ToList();
IDictionary<string, IEnumerable<SelectListItem>> countriesByContinent = new Dictionary<string, IEnumerable<SelectListItem>>();
foreach (var continent in ContinentList)
{
var countryList = new List<SelectListItem>();
foreach (var country in db.Strings.Where(c => c.ParentId == continent.IID))
{
countryList.Add(new SelectListItem { Value = country.IID.ToString(), Text = country.Name });
}
countriesByContinent.Add(continent.Name, countryList);
}
ViewBag.CountriesList = countriesByContinent;
return View();
}
.cshtml就像
@Html.DropDownListFor(model => model.IID, new SelectList(ViewBag.CountriesList as IDictionary<string, IEnumerable<SelectListItem>>), "[Please select a country]")
只有大陆才显示垃圾。
数据库表脚本是
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Strings](
[IID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](30) NOT NULL,
[ParentId] [int] NULL,
[IType] [int] NOT NULL,
CONSTRAINT [PK_Strings] PRIMARY KEY CLUSTERED
(
[IID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
感谢接受任何帮助。
由于 帕塔
答案 0 :(得分:0)
问题是您在控制器中将其转换为视图列表,然后再在视图中转换为视图列表。只需将其放回视图中:
extension String {
/// EZSE: Trims white space and new line characters
public mutating func trim() {
self = self.trimmed()
}
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}