在视图 MVC 中显示列表

Display List in a View MVC

我正在尝试在我的视图中显示我制作的列表,但不断收到:"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]'."

我的控制器:

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

我的看法:

@model IEnumerable<Standings.Models.Teams>

@{
ViewBag.Title = "Standings";
}

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

任何帮助将不胜感激:)

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

但是,最好的方法是将 return 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; }
}

那么您必须将操作方法​​更改为:

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

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

    return View(model);
}

还有,你的观点:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

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

您将错误的模式传递给您查看。您的视图正在寻找 @model IEnumerable<Standings.Models.Teams> 而您正在传递 var model = tm.Name.ToList(); 名单。您必须通过 Teams.

的列表

你必须通过以下模型

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