在Gridview中显示SQL数据库中的数据

时间:2022-05-20 13:57:58

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?

但它没有显示任何数据?我该怎么做?

3 个解决方案

#1


0  

I think you need an editorTemplate for your common object model or use a for sentence and populate an html table

我认为您需要一个editorTemplate用于您的公共对象模型或使用一个句子并填充一个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>

#2


0  

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提供的PagedList.MVC包(https://www.nuget.org/packages/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 - 使用-MVC /排序过滤和寻呼与 - 的实体框架功能于一个-ASP净MVC-应用

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项目的默认格式。

#3


0  

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 />

         }

#1


0  

I think you need an editorTemplate for your common object model or use a for sentence and populate an html table

我认为您需要一个editorTemplate用于您的公共对象模型或使用一个句子并填充一个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>

#2


0  

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提供的PagedList.MVC包(https://www.nuget.org/packages/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 - 使用-MVC /排序过滤和寻呼与 - 的实体框架功能于一个-ASP净MVC-应用

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项目的默认格式。

#3


0  

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 />

         }