如何在mvc中的视图中显示表中的数据库数据

时间:2013-04-23 11:51:59

标签: c# asp.net-mvc

在我的MVC应用程序中,我从数据库中检索数据。我想在表格中显示已退休的数据。 控制器代码:

 public ActionResult MyAccount()
    {

        var user = User.Identity.Name;

       string sThumbnails = "";

        DataSet dsTemplates = new DataSet();

        string qryTemplets = "select * from FileInfo where UserName= '" + user + "'";

        open_Connection();
        SqlDataAdapter daTemplate = new SqlDataAdapter(qryTemplets, conn);
        daTemplate.Fill(dsTemplates, "FileInfo");
        DataTable dtTemplates = new DataTable();
        dtTemplates = dsTemplates.Tables[0];

        foreach (DataRow row in dtTemplates.Rows)
        {

            sThumbnails = sThumbnails +  row["FileName"] +  row["Date"] +  row["Time"] +  row["Info"] ;
            ViewData["thumbs"] = sThumbnails;
        }
        close_Connection();
        return View();
    }

查看代码:

    <div id="formleft" style="border-style: solid; border-color: inherit; border-width: 4px; width:550px; height:500px; position:absolute; top: 345px; left: 348px;">
   <h2 class="heading" style="text-align: center;">Info</h2><%= ViewData["thumbs"] %> </div>

此代码显示数据但我想以表格格式显示它。

如何以表格格式显示数据?

2 个答案:

答案 0 :(得分:3)

不要使用ViewData,使用使用自定义类构建的模型来存储该信息。类似的东西:

public class TableInfo
{
    public string FileName { get; set; }
    public string Date { get; set; } //you might want to change this to DateTime
    public string Time { get; set; }  //this may need changing to TimeSpan or int possibly?
    public string Info { get; set; }
}

然后你可以这样做:

List<TableInfo> tables = dtTemplates.Rows.AsEnumerable()
    .Select(t => new TableInfo
        {
            FileName = row["FileName"],
            Date = row["Date"],
            Time = row["Time"],
            Info = row["Info"]
        })
    .ToList();

    close_Connection();
    return View(tables);

然后在您看来,您可以这样做:

@model List<TableInfo>

if (Model.Count > 0)
{
    <table>
        <tr>
            <td>File Name</td>
            <td>Date</td>
            <td>Time</td>
            <td>Info</td>
        </tr>
        @foreach (TableInfo item in Model)
        {
            <tr>
                <td>@item.FileName</td>
                <td>@item.Date</td>
                <td>@item.Time</td>
                <td>@item.Info</td>
            </tr>
        }
    </table>
}

答案 1 :(得分:0)

在模型中的HTML代码之前添加关注代码

<style> 
   table th {  border: 1px solid black; text-align:center }
   table td {  border: 1px solid black; text-align:center } 
  </style>
相关问题