Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.String]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[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 view:

@model IEnumerable<Standings.Models.Teams>

@{
ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

Any help would be appreciated :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...