在视图MVC中显示列表
我正在尝试显示我在视图中创建的列表,但不断得到:“传入字典的模型项是’System.Collections.Generic.List 1[System.String]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1 [Standings.Models.Teams]’ 1[System.String]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
。“
我的控制器:
public class HomeController : Controller { Teams tm = new Teams(); public ActionResult Index() { var model = tm.Name.ToList(); model.Add("Manchester United"); model.Add("Chelsea"); model.Add("Manchester City"); model.Add("Arsenal"); model.Add("Liverpool"); model.Add("Tottenham"); return View(model); }
我的模特:
public class Teams { public int Position { get; set; } public string HomeGround {get; set;} public string NickName {get; set;} public int Founded { get; set; } public List Name = new List(); }
我的看法:
@model IEnumerable @{ ViewBag.Title = "Standings"; } @foreach (var item in Model) { @item.Name
}
任何帮助,将不胜感激 :)
您的操作方法将模型类型视为List
。 但是,在您看来,您正在等待IEnumerable
。 您可以通过将视图中的模型更改为List
来解决此问题。
但是,最好的方法是从操作方法返回IEnumerable
作为模型。 然后,您不必在视图中更改模型类型。
但是 ,在我看来,你的模型没有正确实现。 我建议你改成它:
public class Team { public int Position { get; set; } public string HomeGround {get; set;} public string NickName {get; set;} public int Founded { get; set; } public string Name { get; set; } }
然后,您必须将操作方法更改为:
public ActionResult Index() { var model = new List(); model.Add(new Team { Name = "MU"}); model.Add(new Team { Name = "Chelsea"}); ... return View(model); }
而且,您的观点:
@model IEnumerable @{ ViewBag.Title = "Standings"; } @foreach (var item in Model) { @item.Name
}
您正在向您查看错误的模式。 您的视图正在寻找@model IEnumerable
并且您正在传递var model = tm.Name.ToList();
名单。 你必须通过团队列表。
你必须通过以下模型
var model = new List(); model.Add(new Teams { Name = new List(){"Sky","ABC"}}); model.Add(new Teams { Name = new List (){"John","XYZ"} }); return View(model);