关系和 MVC3
好的,我有一个包含 TeamID、TeamName
的团队表和一个包含 gameid、team1、team2
列的游戏表。
现在我没有 team1 和 team2 作为 team 表的外键。我知道这会让事情变得更容易,但我想在不这样做的情况下学习。因此,team1
和 team2
是 int 字段。没有约束检查。
因此,当我在视图中显示它时,它会显示 team1 和 team2 列,但我希望它从 team 表中提取团队名称,而不是显示整数 ID。
好吧,在我看来,我有以下内容:
@model IEnumerable<Betting.Models.Bets>
@{
ViewBag.Title = "List of Games";
}
@{
var grid = new WebGrid(source: Model, defaultSort: "EndDate", rowsPerPage: 3);
}
<h2>
Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<h2>
Betting List</h2>
<div id="grid">
@grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Subject"),
grid.Column("Team1"),
grid.Column("Team2")
)
)
</div>
我的控制器非常简单:
public ViewResult Index()
{
return View(db.Bets.ToList());
}
okay so I have a teams table with TeamID, TeamName
and a games table with columns gameid, team1, team2
.
Now I dont have team1 and team2 as Foreign keys to the teams table. I understand this will make it easier but I want to learn without doing that. So team1
, and team2
are int fields. There is no constraint check.
So when I display it in my view, it displays the team1 and team2 columns but instead of displaying the integer ID, I want it to pull the team name from the teams table.
okay in my view I have the following:
@model IEnumerable<Betting.Models.Bets>
@{
ViewBag.Title = "List of Games";
}
@{
var grid = new WebGrid(source: Model, defaultSort: "EndDate", rowsPerPage: 3);
}
<h2>
Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<h2>
Betting List</h2>
<div id="grid">
@grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Subject"),
grid.Column("Team1"),
grid.Column("Team2")
)
)
</div>
And my controller is really simple:
public ViewResult Index()
{
return View(db.Bets.ToList());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
始终在 ASP.NET MVC 中使用视图模型,您不会遇到此类问题:
然后在控制器操作中执行必要的映射/查询以填充此视图模型:
最后在视图中:
就模型之间的映射而言视图模型 AutoMapper 可以大大简化这项任务。
Always use view models in ASP.NET MVC and you won't have such problems:
then in the controller action do the necessary mapping/querying in order to populate this view model:
finally in the view:
As far as the mapping between your models and view models is concerned AutoMapper could greatly simplify this task.