0

okay so I have a teams table with TeamID, TeamName and a games table with columns gameid, team1, team2.

Now I dont have team1 and team2 as Foreign keys to the teams table. I understand this will make it easier but I want to learn without doing that. So team1, and team2 are int fields. There is no constraint check.

So when I display it in my view, it displays the team1 and team2 columns but instead of displaying the integer ID, I want it to pull the team name from the teams table.

okay in my view I have the following:

   @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>

And my controller is really simple:

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 に答える