2011-05-15 88 views
0

好吧,所以我有一個與TeamID, TeamName和遊戲桌列隊gameid, team1, team2列表的表。關係和MVC3

現在我沒有team1和team2作爲對外表的外鍵。我明白這會讓事情變得更容易,但我不想那樣做,我想學習。所以team1team2是int字段。沒有限制檢查。

因此,當我將它顯示在我的視圖中時,它顯示了team1和team2列,但不是顯示整數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()); 
} 

回答

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可以大大簡化這一任務。