MVC从数据库中检索数据并在视图中显示它

时间:2013-09-29 07:15:37

标签: asp.net-mvc asp.net-mvc-4

我不是100%如何解决这个问题。

我有一个基本的控制器,它从名为transactions

的表中检索数据

CONTROLLER private NWBA_DBEntities db = new NWBA_DBEntities();

    public ActionResult Index()
    {
        var statements = db.Transactions.ToList();
        return View(statements);

    }

我有基本型号:

public class StatementModel
{

    [StringLength(50)]
    [Display(Name="Transaction Type: ")]
    public string TransactionType { get; set; }

    [StringLength(50)]
    [Display(Name = "AccountNumber")]
    public string AccountNumber { get; set; }



}

我的问题出在View,我似乎无法在表中显示值:

@model Login.Models.StatementModel

@{
    ViewBag.Title = "Statements";
}


<h2>Index</h2>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.TransactionType)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.AccountNumber)
        </th>

        <th></th>
    </tr>

    @foreach (var item in Model) 
    {
    <tr>

    </tr>
}
</table>

有人可以帮忙吗

1 个答案:

答案 0 :(得分:4)

public ActionResult Index()
    {
        var statementModel = from s in db.Transactions
                            select new StatementModel
                            {
                                TransactionType  = s.TransactionType,
                                AccountNumber = s.AccountNumber
                            }
        return View(statementModel);

    }