关系和MVC3

时间:2011-05-15 23:59:51

标签: asp.net asp.net-mvc-3 webgrid

好吧,我有一个包含TeamID, TeamName的团队表和一个包含gameid, team1, team2列的游戏表。

现在我没有team1和team2作为team表的外键。我明白这会让事情变得更容易,但我想在不这样做的情况下学习。因此team1team2是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());
}

1 个答案:

答案 0 :(得分: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可以大大简化此任务。