在视图MVC中显示列表

FiF*_*TeR 10 c# model-view-controller asp.net-mvc list

我正在尝试显示我在视图中创建的列表,但仍然得到:"传入字典的模型项的类型为'System.Collections.Generic.List 1[System.String]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1 [Standings.Models.Teams]'."

我的控制器:

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);
    }
Run Code Online (Sandbox Code Playgroud)

我的模特:

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>();
}
Run Code Online (Sandbox Code Playgroud)

我的看法:

@model IEnumerable<Standings.Models.Teams>

@{
ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激 :)

Far*_*yev 21

您的操作方法将模型类型视为List<string>.但是,在你看来,你在等待IEnumerable<Standings.Models.Teams>.您可以通过将视图中的模型更改为来解决此问题List<string>.

但是,最好的方法是IEnumerable<Standings.Models.Teams>从动作方法返回作为模型.然后,您不必在视图中更改模型类型.

但是,在我看来,你的模型没有正确实现.我建议你改成它:

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; }
}
Run Code Online (Sandbox Code Playgroud)

然后,您必须将操作方法​​更改为:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

而且,您的观点:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}
Run Code Online (Sandbox Code Playgroud)