Display List in MVC View

I try to display the list that I made in my view, but keep getting: "The model element passed to the dictionary is of type" System.Collections.Generic.List 1[System.String]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [Standings.Models.Teams] "".

My controller:

 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); } 

My 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<string> Name = new List<string>(); } 

My opinion:

 @model IEnumerable<Standings.Models.Teams> @{ ViewBag.Title = "Standings"; } @foreach (var item in Model) { <div> @item.Name <hr /> </div> } 

Any help would be appreciated :)

+6
source share
2 answers

Your action method considers the model type as List<string> . But, in your opinion, you are waiting for IEnumerable<Standings.Models.Teams> . You can solve this problem by changing the model in your opinion to List<string> .

But a better solution would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you should not change the type of model in your view.

But , in my opinion, your models are incorrectly implemented. I suggest you change it as:

 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; } } 

Then you should change your action method as follows:

 public ActionResult Index() { var model = new List<Team>(); model.Add(new Team { Name = "MU"}); model.Add(new Team { Name = "Chelsea"}); ... return View(model); } 

And, your opinion:

 @model IEnumerable<Standings.Models.Team> @{ ViewBag.Title = "Standings"; } @foreach (var item in Model) { <div> @item.Name <hr /> </div> } 
+13
source

You are viewing the wrong mode. Your view searches for @model IEnumerable<Standings.Models.Teams> , and you pass a list of names var model = tm.Name.ToList(); . You need to pass the Team list.

You need to pass the following model

 var model = new List<Teams>(); model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}}); model.Add(new Teams { Name = new List<string>(){"John","XYZ"} }); return View(model); 
0
source

Source: https://habr.com/ru/post/983572/


All Articles