Display List in a View MVC

后端 未结 2 745
遥遥无期
遥遥无期 2020-12-05 08:41

I\'m trying to display the list I made in my view but keep getting : \"The model item passed into the dictionary is of type \'System.Collections.Generic.List1[System.S

相关标签:
2条回答
  • 2020-12-05 08:59

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

    But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

    But, in my opinion your models are not correctly implemented. I suggest you to 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 must change your action method as:

    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 view:

    @model IEnumerable<Standings.Models.Team>
    
    @{
         ViewBag.Title = "Standings";
    }
    
    @foreach (var item in Model)
    {
        <div>
            @item.Name
            <hr />
        </div>
    }
    
    0 讨论(0)
  • 2020-12-05 09:03

    You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

    You have to pass 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 讨论(0)
提交回复
热议问题