我是MVC的新手,我正在尝试为某个View创建一个ViewModel。我很难过,无法在网上找到一个简单的解释,说明如何制作一个包含两个简单表格的视图 - 一个显示Player.cs中所有玩家的列表,另一个显示季节中所有季节的列表。 CS。我能够在使用EF的单独视图中执行此操作,但无法创建一个显示两个表的视图。感谢您帮助MVC的新手,我希望这将有助于其他初学者。
这是我的三个型号。首先是Player.cs
using System;
using System.Collections.Generic;
namespace TheFlyingPig.Models
{
public class Player
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Stat> Stats { get; set; }
}
}
下一个模型是Season.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace TheFlyingPig.Models
{
public class Season
{
public int SeasonID { get; set; }
public string SeasonName { get; set; }
public virtual ICollection<Stat> Stats { get; set; }
}
}
第三个模型是Stat.cs
namespace TheFlyingPig.Models
{
public class Stat
{
public int StatID { get; set; }
public int SeasonID { get; set; }
public int PlayerID { get; set; }
public int Hits { get; set; }
public virtual Season Season { get; set; }
public virtual Player Player { get; set; }
}
}
以下是我要创建的ViewModel:TeamStat.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using TheFlyingPig.Models;
namespace TheFlyingPig.ViewModels
{
public class TeamStat
{
public List<Player> Players { get; set; }
public List<Season> Seasons { get; set; }
}
}
这是我的控制器:
using System.Data;
using System.Data.Entity;
using System.Net;
using TheFlyingPig.Models;
using TheFlyingPig.ViewModels;
namespace TheFlyingPig.Controllers
{
public class HomeController : Controller
{
private SoftballContext db = new SoftballContext();
public ActionResult Index()
{
return View();
}
public ActionResult TeamStat()
{
var players = db.Players().ToList();
var seasons = db.Seasons().ToList();
var view = new TeamStat(players, seasons);
return View(view);
}
}
}
以下是我的观点:TeamStat.cshtml
@model TheFlyingPig.ViewModels.TeamStat
@{
ViewBag.Title = "Team Stats";
}
<h2>Team Stats</h2>
@foreach (var player in Model._players)
{
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>@player.FirstName</td>
<td>@player.LastName</td>
</tr>
</tbody>
</table>
}
<br /><br /><br />
@foreach (var season in Model._seasons)
{
<table>
<thead>
<tr>
<th>Season Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>@season.SeasonName</td>
</tr>
</tbody>
</table>
}
答案 0 :(得分:5)
首先,在返回视图之前,您当前没有设置视图模型的属性(您没有接受2个参数的构造函数)
public ActionResult TeamStat()
{
var players = db.Players().ToList();
var seasons = db.Seasons().ToList();
var view = new TeamStat()
{
Players = players,
Seasons = seasons
};
return View(view);
}
其次,您的观点指的是不存在的属性_players
和_seasons
。它应该是
@foreach (var player in Model.Players) { ....
和
@foreach (var player in Model.Seasons) { ....