如何使用 MS 数据库(ASP.NET Core MVC)通过表格显示信息?

Posted

技术标签:

【中文标题】如何使用 MS 数据库(ASP.NET Core MVC)通过表格显示信息?【英文标题】:How to display information with a table using MS database (ASP.NET Core MVC)? 【发布时间】:2021-12-28 13:47:11 【问题描述】:

我创建了这个项目,它有一个使用身份的注册和登录页面。我关注了这个视频。视频:https://www.youtube.com/watch?v=CzRM-hOe35o

我想测试一个想法,所以我想显示我在数据库中的用户信息。但是,我想出如何显示信息的唯一方法是使用 _LoginPartial.cshtml 文件中的用户管理器选项 (@UserManager.GetUserAsync(User).Result.FirstName)。在我了解更多信息的过程中,我看到了这个视频,它教你如何用表格显示数据库中的信息。视频:https://www.youtube.com/watch?v=5wLfTRx2-FI

我有一些问题,他使用的是 Sqlite,而我使用的是 Microsoft SQL Server Management Studio 18。我尝试按照他的方式将列表添加到家庭控制器中。但是,它并没有像他那样工作

为了使用他从数据库中显示信息的方式,我该如何适应?或者有没有更简单的方式来显示信息?

这是我的代码。如果您需要更多信息,请告诉我

Index.cshtml:

@
    ViewData["Title"] = "Home Page";


<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

家庭控制器:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using The_Bank_of_Cardinal.Areas.Identity.Data;
using The_Bank_of_Cardinal.Models;

namespace The_Bank_of_Cardinal.Controllers

    public class HomeController : Controller
    
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        
            _logger = logger;
        

        public IActionResult Index()
        
            
            return View();
        

        public IActionResult Privacy()
        
            return View();
        


        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        
            return View(new ErrorViewModel  RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier );
        
    

位于 Areas>Identity>Data 文件夹中的模型

CardinalUser.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace The_Bank_of_Cardinal.Areas.Identity.Data

    // Add profile data for application users by adding properties to the CardinalUser class
    public class CardinalUser : IdentityUser
    
        [PersonalData]
        [Column(TypeName ="nvarchar(100)")]
        public string FirstName  get; set; 

        [PersonalData]
        [Column(TypeName = "nvarchar(100)")]
        public string LastName  get; set; 

        [PersonalData]
        [Column(TypeName = "nvarchar(500)")]
        public string Street  get; set; 

        [PersonalData]
        [Column(TypeName = "nvarchar(100)")]
        public string City  get; set; 

        [PersonalData]
        [Column(TypeName = "nvarchar(100)")]
        public string State  get; set; 

        [PersonalData]
        [Column(TypeName = "nvarchar(100)")]
        public string ZipCode  get; set; 

        [PersonalData]
        [Column(TypeName = "nvarchar(100)")]
        public string LoginName  get; set; 

        [PersonalData]
        [Column(TypeName = "nvarchar(100)")]
        public string SSN  get; set; 

        [PersonalData]
        [Column(TypeName = "int")]
        public int AccountBalance  get; set; 








    

CardinalDbContext 也位于同一文件夹中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using The_Bank_of_Cardinal.Areas.Identity.Data;

namespace The_Bank_of_Cardinal.Data

    public class CardinalDbContext : IdentityDbContext<CardinalUser>
    
        public CardinalDbContext(DbContextOptions<CardinalDbContext> options)
            : base(options)
        
        

        protected override void OnModelCreating(ModelBuilder builder)
        
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        
    

_LoginPartial.cshtml:

@using Microsoft.AspNetCore.Identity
@using The_Bank_of_Cardinal.Areas.Identity.Data

@inject SignInManager<CardinalUser> SignInManager
@inject UserManager<CardinalUser> UserManager


<ul class="navbar-nav">

    @if (SignInManager.IsSignedIn(User))
    
        <li class="nav-item">
            <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserAsync(User).Result.FirstName @UserManager.GetUserAsync(User).Result.LastName Balance: $@UserManager.GetUserAsync(User).Result.AccountBalance </a>
        </li>
        <li class="nav-item">
            <form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new  area = "" )">
                <button id="logout" type="submit" class="nav-link btn btn-link text-dark">Logout</button>
            </form>
        </li>
    
    else
    
        <li class="nav-item">
            <a class="nav-link text-dark" id="register" asp-area="Identity" asp-page="/Account/Register">Register</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" id="login" asp-area="Identity" asp-page="/Account/Login">Login</a>
        </li>
    
</ul>

程序.cs:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace The_Bank_of_Cardinal

    public class Program
    
        public static void Main(string[] args)
        
            CreateHostBuilder(args).Build().Run();
        

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                
                    webBuilder.UseStartup<Startup>();
                );
    

startup.cs:

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

namespace The_Bank_of_Cardinal

    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.AddControllersWithViews();
            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("/Home/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.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "controller=Home/action=Index/id?");
                endpoints.MapRazorPages();
            );
        
    

【问题讨论】:

在 Startup.cs 中有一个 ConfigureService 方法。将您的数据库上下文添加到那里的 SQL 提供程序: services.AddDbContext(o => o.UseSqlServer("MyConnectionString"); ); 我可以看到您在_LoginPartial.cshtml中有代码来显示用户信息。您是否收到任何错误或输出未显示? @rahatur 我正在从登录用户那里获取信息。但我想显示数据库中的所有内容。不仅来自登录用户 FirstName、LAstName、Balance 来自数据库对吗? @Rahatur 是的 【参考方案1】:
List<User> allusers = await UserManager.Users.ToListAsync();

现在枚举用户列表并呈现数据

foreach(User u in allusers)

    u.FirstName + " " + u.LastName + " " + u.AccountBalance + "<br/>"

【讨论】:

我会把这个放在哪里 您希望用户信息列表显示的位置。在 UI 中,为什么不将它放在 _LoginPartial.cshtml 中 &lt;ul class="navbar-nav"&gt; 行之后?

以上是关于如何使用 MS 数据库(ASP.NET Core MVC)通过表格显示信息?的主要内容,如果未能解决你的问题,请参考以下文章

为 ASP.NET Core 5.0 - EF Core 5.0 Web App 配置 PostgreSQL 连接字符串以在 MS 或 Linux 云上运行?

ASP.NET Core中的缓存[1]:如何在一个ASP.NET Core应用中使用缓存

如何先用asp.net身份框架数据库将asp.net mvc迁移到asp.net core

如何使用 asp.net 从客户端读取 ms-access 数据库文件

使用 ASP.NET Core 和 Entity Framework Core 进行集成测试 - 如何在每次测试时恢复数据库中的测试数据?

如何使用 Asp.Net Core 2.2 / IdentityServer4 / SP.NET Core Identity 手动散列密码