【问题标题】:relationships and MVC3关系和 MVC3
【发布时间】:2011-05-15 23:59:51
【问题描述】:

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

现在我没有 team1 和 team2 作为 teams 表的外键。我知道这会让事情变得更容易,但我想不这样做就学习。所以team1team2 是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());
}

【问题讨论】:

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


    【解决方案1】:

    始终在 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 可以大大简化这项任务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      相关资源
      最近更新 更多