如何在MVC视图中的表中显示数据库数据 [英] how to display database data in tables in view in mvc
本文介绍了如何在MVC视图中的表中显示数据库数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的MVC应用程序中,正在从数据库中检索数据.我想在表中显示退休数据. 控制器代码:
In my MVC application am retrieving data from Database. I want to display the retired data in tables. controller code:
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>
此代码显示数据,但我想以表格格式显示它.
This code displays the data But i want to display it in tabular format.
如何以表格格式显示数据?
How can i display the data in tabular format?
推荐答案
不要使用ViewData
,请使用使用自定义类构建的模型来存储该信息.像这样:
Don't use ViewData
, use a Model built using a custom class to store that information. Something like:
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; }
}
然后您可以执行以下操作:
Then you can do:
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);
然后您可以执行以下操作:
Then in your view you can do:
@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>
}
这篇关于如何在MVC视图中的表中显示数据库数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文