C# 在 Gridview 中显示 SQL 数据库中的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12311626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show data from SQL database in Gridview
提问by user1348351
I want to show data in grid view using 3 tables in SQL database.
我想使用 SQL 数据库中的 3 个表在网格视图中显示数据。
first I created Model
首先我创建了模型
public class common
{
public Artist Artist { get; set; }
public Album Album { get; set; }
public Genre Genre { get; set; }
}
Then This is the Controller
那么这是控制器
public ActionResult Show1()
{
var query = from a in DB.Album
join b in DB.Artists
on a.ArtistId equals b.ArtistId
join c in DB.Genre
on a.GenreId equals c.GenreId
where (b.ArtistId == 2)
select new common { Album = a, Artist = b, Genre = c };
return View(query.ToList());
}
}
After that this is my View
之后这是我的观点
@model IEnumerable<test1.Models.common>
@{
ViewBag.Title = "Show1";
}
<h2>Show1</h2>
<div>
@{
var grid = new WebGrid(Model, defaultSort:"Name");
}
@grid.GetHtml()
</div>
But it doesn't show any data? How can I do it?
但它没有显示任何数据?我该怎么做?
回答by hagensoft
I think you need an editorTemplate for your common object model or use a for sentence and populate an html table
我认为您需要一个用于公共对象模型的 editorTemplate 或使用 for 语句并填充 html 表
for example...
例如...
<table summary="">
<thead>
<tr>
<th></th>
<th>
Account No.
</th>
<th>
Customer Name
</th>
<th class="SingleCheckBox">
Is Approved
</th>
<th class="SingleCheckBox">
Is Locked out
</th>
<th>
Last Login
</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); ++i)
{
var item = Model[i];
bool isSelected = item.AccountNo == selectedAccountNo;
<tr>
<td>@Html.RadioButton("selectedUserName", item.UserName, isSelected, new { name = "selectedUserName" })</td>
<td>
@Html.DisplayFor(model => model[i].UserName)
@Html.HiddenFor(model => model[i].UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td class="SingleCheckBox">
@Html.CheckBoxFor(model => model[i].IsApproved)
</td>
<td class="SingleCheckBox">
@if (item.IsLockedOut)
{
@Html.CheckBoxFor(model => model[i].IsLockedOut);
}
else
{
@Html.CheckBoxFor(model => model[i].IsLockedOut);
}
</td>
<td class="last-child">
@(TimeZoneInfo.ConvertTime(DateTime.SpecifyKind(item.LastLoginDate, DateTimeKind.Utc), timeZoneInfo).ToString())
</td>
</tr>
}
</tbody>
</table>
回答by CodeBreaker
I believe that the best answer to your question is yet another question: "Why a WebGrid?"
我相信对你的问题最好的答案是另一个问题:“为什么是 WebGrid?”
If you refer to the default functionality of a newly created MVC project, you will see that the Index.cshtml will use a table (as suggested in the answer provided by @hagensoft). It has been my experience that when items are properly scaffolded for an MVC project in Visual Studio I have had to do very little work to get the list of models to display nicely, even paginated if necessary.
如果您参考新创建的 MVC 项目的默认功能,您将看到 Index.cshtml 将使用一个表(如@hagensoft提供的答案中所建议)。根据我的经验,当项目在 Visual Studio 中为 MVC 项目正确搭建脚手架时,我只需要做很少的工作就可以很好地显示模型列表,甚至在必要时进行分页。
To make better use of pagination, if that is what you are after, I have made great use of the PagedList.MVC package available through NuGet (https://www.nuget.org/packages/PagedList.Mvc/). There is plenty of documentation related to the functionality provided by PagedList, and PagedList, along with the table suggestion/default view behavior with new MVC projects in Visual Studio, works wonders along side of any sorting, searching, or similar functionality that you would like to provide within your app.
为了更好地利用分页,如果这就是您所追求的,我充分利用了通过 NuGet ( https://www.nuget.org/packages/PagedList.Mvc/)提供的 PagedList.MVC 包。有大量与 PagedList 和 PagedList 提供的功能相关的文档,以及 Visual Studio 中新 MVC 项目的表格建议/默认视图行为,可以与您想要的任何排序、搜索或类似功能一起创造奇迹在您的应用程序中提供。
A fantastic tutorial that I refer to about Sorting, Filtering, and Paging can be found here: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
我参考的关于排序、过滤和分页的精彩教程可以在这里找到:https: //docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef -using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
If you are insistent about using a WebGrid/GridView, I would suggest perhaps moving the database call out of the controller and directly into the Razor view itself, or try sending back an ObervableCollection<>, not a List<>, of a dedicated ViewModel from the Controller.
如果您坚持使用 WebGrid/GridView,我建议也许将数据库调用从控制器中移出并直接移入 Razor 视图本身,或者尝试发回专用 ViewModel 的 ObervableCollection<>,而不是 List<>从控制器。
The moral of the story here is to not venture far from the provided path. Try to use the tools that are given to you and follow the default format for MVC projects.
这里故事的寓意是不要冒险远离提供的路径。尝试使用提供给您的工具并遵循 MVC 项目的默认格式。
回答by Kasunjith Bimal
First Add Jquery in your view
首先在您的视图中添加 Jquery
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
If you want to style Add Style
如果你想样式添加样式
<style type="text/css">
.webGrid { margin: 4px; border-collapse: collapse; width: 500px; background-color:#FCFCFC;}
.header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
.webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
.alt { background-color: #E4E9F5; color: #000; }
.gridHead a:hover {text-decoration:underline;}
.description { width:auto}
.select{background-color: #389DF5}
</style>
Add Model in your view
在您的视图中添加模型
@{
test1.Models.common Common = new test1.Models.common();
}
Add Code in your view
在您的视图中添加代码
@{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
@grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("Id", "Id"),
grid.Column("Name", "Name"),
grid.Column("Description", "Description"),
))
@if (grid.HasSelection)
{
common= (test1.Models.common)grid.Rows[grid.SelectedIndex].Value;
<b>Id</b> @common.Artist.Id<br />
<b>Name</b> @common.Album.Name<br />
<b>Description</b> @common.Album.Description<br />
}
</div>
Edit this section According to your Model details
根据您的模型详细信息编辑此部分
@if (grid.HasSelection)
{
common= (test1.Models.common)grid.Rows[grid.SelectedIndex].Value;
<b>Id</b> @common.Artist.Id<br />
<b>Name</b> @common.Album.Name<br />
<b>Description</b> @common.Album.Description<br />
}
回答by Onur Gelmez
Because of your model it doesn't show anything. Webgrid doesn't know how to render your Artist or Album or Genre table model.
由于您的模型,它没有显示任何内容。Webgrid 不知道如何渲染您的艺术家、专辑或流派表模型。
public ActionResult Show1()
{
var query = from a in DB.Album
join b in DB.Artists
on a.ArtistId equals b.ArtistId
join c in DB.Genre
on a.GenreId equals c.GenreId
where (b.ArtistId == 2)
select new common { AlbumName = a.AlbumName, ArtistName = b.ArtistName, GenreName = c.GenreName /* ... other props */ };
return View(query.ToList());
}
public class common
{
public string ArtistName { get; set; }
public string AlbumName { get; set; }
public string GenreName { get; set; }
//other props and not tables, use like string, int, decimal...
}

