0

好的,所以我有一个带有列的团队表TeamID, TeamName和一个带有列的游戏表gameid, team1, team2

现在我没有 team1 和 team2 作为 teams 表的外键。我知道这会让事情变得更容易,但我想不这样做就学习。所以team1, 和team2是 int 字段。没有约束检查。

因此,当我在视图中显示它时,它会显示 team1 和 team2 列,但不是显示整数 ID,而是希望它从 teams 表中提取团队名称。

好吧,在我看来,我有以下几点:

   @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());
}
4

1 回答 1

0

始终在 ASP.NET MVC 中使用视图模型,您不会遇到这样的问题:

public class TeamViewModel
{
    public string Team1Name { get; set; }
    public string Team2Name { get; set; }
    public string Subject { get; set; }
}

然后在控制器操作中进行必要的映射/查询以填充此视图模型:

public ActionResult Index()
{
    // Fetch the data here, depending on the ORM you are using
    // perform the necessary joins so that you have the team names
    IEnumerable<Betting.Models.Bets> model = ...

    // map the model to the view model previously defined
    IEnumerable<TeamViewModel> viewModel = ...

    // pass the view model to the view for display
    return View(viewModel);
}

最后在视图中:

@model IEnumerable<TeamViewModel>
@{
    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("Team1Name"),
            grid.Column("Team2Name")          
        )
    )
</div>

就模型和视图模型之间的映射而言,AutoMapper可以大大简化这项任务。

于 2011-05-16T06:37:25.027 回答