我在数据库中有这个表:
我正在尝试在浏览器中显示值(ModuleID
和DateEntered
)作为表格。
我正在使用viewbag将值传递给我的视图,这不是正确的方法,因为我现在只有一行。我现在正在做的是
public ActionResult Index()
{
var modules = (from entries in _db.Modules
orderby entries.DateEntered
select entries);
ViewBag.entries = modules.ToList();
return View();
}
如何从上图中的表中获取所有行并将其传递给视图? 在我看来,我目前有:
@using BootstrapSupport
@model Sorama.DataModel.SIS.ModuleStock.Module
@{
ViewBag.Title = "Index";
Layout = "~/Views/shared/_BootstrapLayout.basic.cshtml";
}
<table class="table table-striped">
<caption></caption>
<thead>
<tr>
<th>
Module ID
</th>
<th>
Date Entered
</th>
</tr>
</thead>
<tr>
@foreach (var entry in ViewBag.entries)
{
<td>@entry.ModuleId</td>
<td>@entry.DateEntered</td>
}
<td>
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Action
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Details", "Details")</li>
@if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Admin"))
{
<li class="divider"></li>
<li>@Html.ActionLink("Edit", "Edit")</li>
<li>@Html.ActionLink("Delete", "Delete")</li>
}
</ul>
</div>
</td>
</tr>
</table>
这显示整行的值,而不仅仅是{ModuleID
和DateEntered
)
这是我在浏览器中获得的。
总而言之,我希望从表中获取所有行,但只能获取特定列。 在目前的情况下没有发生这种情况。 建议?
答案 0 :(得分:2)
你误读了你的结果。共有3条记录,每行显示2个字段。您在视图中有<tr>
个单身,并在ViewBag
代码中插入<td>
的值。您应该为<tr>
中的每条记录添加新的ViewBag
。
看起来应该更像这样:
@foreach (var entry in ViewBag.entries)
{
<tr>
<td>@entry.ModuleId</td>
<td>@entry.DateEntered</td>
<td>
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Action<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Details", "Details")</li>
@if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Admin"))
{
<li class="divider"></li>
<li>@Html.ActionLink("Edit", "Edit")</li>
<li>@Html.ActionLink("Delete", "Delete")</li>
}
</ul>
</div>
</td>
</tr>
}
答案 1 :(得分:1)
试试这个
public ActionResult Index()
{
ABCList abc=new ABCList();
var modules = (from entries in _db.Modules
orderby entries.DateEntered
select new ABC {
id=entries.id,
ModuleTypeId=entries.ModuleTypeId,
ModuleId=entries.ModuleId,
DataEntered=entries.DataEntered
});
abc.settings = modules.ToList();
return View();
}
public class ABC
{
public long Id{ get; set; }
public long ModuleTypeId{ get; set; }
public string ModuleId{get;set;}
public DateTime DataEntered{ get; set; }
}
public class ABCList{
public List<ABC> Settings { get; set; }
}
查看
@model ABCList
@foreach (var entry in Model.Settings)
{
<tr>
<td>@entry.ModuleId</td>
<td>@entry.DateEntered</td>
<td>
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Action<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Details", "Details")</li>
@if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Admin"))
{
<li class="divider"></li>
<li>@Html.ActionLink("Edit", "Edit")</li>
<li>@Html.ActionLink("Delete", "Delete")</li>
}
</ul>
</div>
</td>
</tr>
}