微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Visual Studio Code 中的 asp.net core mvc 中实现 jquery 插件数据表

如何解决在 Visual Studio Code 中的 asp.net core mvc 中实现 jquery 插件数据表

我在 MysqL 数据库中有条目,但我无法在数据库上实现 jquery 数据表插件,以便在浏览器中将该表显示为 jquery 插件数据表(服务器端处理)。我该如何实施?

这是文件文件夹。

模型

  1. 课程.cs
using System.ComponentModel.DataAnnotations.Schema;
namespace ContosoUniversity.Models
{
   public class Course
   {
       [DatabaseGenerated(DatabaseGeneratedOption.None)]
       public int CourseID {get;set;}
       public string Title {get;set;}
       public int Credits {get;set;}

       public ICollection<Enrollment> Enrollments {get;set;}
   } 
}
  1. 注册.cs
{
    public enum Grade
    {
        A,B,C,D,F
    }
    public class Enrollment
    {
        public int EnrollmentID {get;set;}
        public int CourseID {get;set;}
        public int StudentID{get;set;}
        public Grade? Grade {get;set;}

        public Course Course {get;set;}
        public Student Student {get;set;}
    }
}

3)Student.cs

using System.Collections.Generic;
namespace ContosoUniversity.Models
{
    public class Student
    {
        public int ID {get;set;}
        public String LastName {get;set;}
        public String FirstName {get;set;}
        public DateTime EnrollmentDate {get;set;}
        public ICollection<Enrollment> Enrollments { get; set; }
    }
}

观看次数 在 Pages/Shared/Layout.cshtml

<html lang="en">
<head>
    <Meta charset="utf-8" />
    <Meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>@ViewData["Title"] - Contoso University</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom Box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-page="/Index">ContosoUniversity</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/About">About</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Students/Index">Students</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Courses/Index">Courses</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Teachers/Index">Teachers</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Departments/Index">Departments</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2021 - Contoso University - <a asp-area="" asp-page="/Privacy">Privacy</a>
        </div>
    </footer>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @await RenderSectionAsync("Scripts",required: false)
</body>
</html>

ContosoUniversity.csproj 文件


  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <packagereference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.0-*" />
    <packagereference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0-*">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </packagereference>
    <packagereference Include="Microsoft.EntityFrameworkCore.sqlite" Version="5.0.0-*" />
    <packagereference Include="Microsoft.EntityFrameworkCore.sqlServer" Version="5.0.0-*" />
    <packagereference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0-*">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </packagereference>
    <packagereference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.0-*" />
    <packagereference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.1" />
    <packagereference Include="Microsoft.Composition" Version="1.0.30" ExcludeAssets="All" />
    <packagereference Include="System.Composition" Version="1.0.31" />
    
  </ItemGroup>

</Project>

在 .vscode/launch.json 文件

    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information,visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0","configurations": [
        {
            "name": ".NET Core Launch (web)","type": "coreclr","request": "launch","prelaunchTask": "build","program": "${workspaceFolder}/bin/Debug/<net5.0>/<ContosoUniversity.dll>","args": [],"cwd": "${workspaceFolder}","externalConsole": true,"stopAtEntry": false,"serverReadyAction": {
                "action": "openExternally","pattern": "\\bNow listening on:\\s+(https?://\\S+)"
            },"env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },"sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        },{
            "name": ".NET Core Launch (web)","program": "${workspaceFolder}/bin/Debug/net5.0/ContosoUniversity.dll",{
            "name": ".NET Core Attach","request": "attach","processId": "${command:pickProcess}"
        }
    ]
}

Startup.cs 文件

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ContosoUniversity
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

index.cshtml 文件

@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="row mb-auto">
    <div class="col-md-4">
        <div class="row no-gutters border mb-4">
            <div class="col p-4 mb-4">
                <p class="card-text">
                    Contoso University is a simple application that demonstrates how to use Entity FRamework Core in an ASP.NET CORE RAZOR PAGES web app.
                </p>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="row no-gutters border mb-4">
            <div class="col p-4 d-flex flex-column position-static">
                <p class="card-text mb-auto">
                    You can build the app by following the steps in series of tutorials.
                </p>
                <p>
                    <a href="https://docs.microsoft.com/aspnet/core/data/ef-rp/intro" class="streched-link">See The Tutorials</a>
                </p>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="row no-gutters border mb-4">
            <div class="col p-4 d-flex flex-column">
                <p class="card-text mb-auto">
                    You can understand complete project from GitHub
                </p>
                <p>
                    <a href="https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/data/ef-rp/intro/samples" class="streched-link">Project Source Code
                    </a>
                </p>
            </div>
        </div>
    </div>
</div>

解决方法

这是一个演示,用于展示带有 DataTable 的课程: 控制器(我用假数据测试):

public IActionResult LoadData1()
        {
            List<Course> l = new List<Course> { new Course {  CourseID=1,Credits=1,Title="Maths"},new Course { CourseID = 2,Credits = 2,Title = "English" },new Course { CourseID = 3,Credits = 3,Title = "PE" } };
            return Json(l);
        }

View(需要在dataTables之前加载jquery,列中需要首字母小写):

<table id="myDataTable">
    <thead>
        <tr>
            <td>CourseID</td>
            <td>Title</td>
            <td>Credits</td>

        </tr>
    </thead>
    <tbody>
    </tbody>

</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#myDataTable').DataTable({
                ajax: {
                    url: '/Test1/LoadData1',"dataSrc": ""
                },columns: [
                    { data: "courseID" },{ data: "title" },{ data: "credits" }

                ]
            });
        });


    </script>

结果: enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。