2011-05-15 16 views
0

大丈夫です。TeamID, TeamNameのチームテーブルと、gameid, team1, team2という列のゲームテーブルがあります。関係とMVC3

チームテーブルには外部キーとしてteam1とteam2がありません。私はこれが簡単になることを理解していますが、私はそれをやることなく学びたいと思っています。したがって、team1およびteam2は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大幅にこの作業を簡素化することができます。