模型未从数据库获取数据

问题描述 投票:0回答:1

在我的 ASP.NET Core MVC 应用程序中,我想访问数据库,但我的代码返回错误。 不明白,哪里出了问题。

程序.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddDbContext<ApplicationDBContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();

UserEmployeeController.cs

public class UserEmployeeController : Controller
{
    private readonly ApplicationDBContext _context;

    public UserEmployeeController(ApplicationDBContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        var employee = _context.UserEmployee.FirstOrDefault();
        return View(employee);
    }
}

索引.cshtml

@page

@model JobSearcher.Models.UserEmployee

@{
    ViewData["Title"] = "Карточка сотрудника";
}

<h1>@ViewData["Title"]</h1>

<div class="album py-5 bg-light">
    <div class="container">
        <div class="row">
            @Model.JopTitle;
        </div>
    </div>
</div>

UserEmployee.cs

public class UserEmployee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid UserEmployeeId { get; set; }
    public string JopTitle { get; set; }
}

ApplicationDBContext.cs

public class ApplicationDBContext : DbContext
{
    public DbSet<UserEmployee> UserEmployee { get; set; }

    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options) { }
}

_Layout.cshtml

<li class="nav-item">
      <a class="nav-link text-dark" asp-area="" asp-page="/UserEmployee/Index">Employee</a>
   @* <a class="nav-link text-dark" asp-area="" asp-controller="UserEmployee" asp-action="Index">Employee</a> *@
</li>
c# .net asp.net-mvc asp.net-core model-view-controller
1个回答
0
投票

如果 Index.cshtml 是一个视图,请尝试从 Index.cshtml 中删除 @page。

此外,您可以为 mvc 添加路由,例如:

builder.Services.AddControllersWithViews();
...
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
© www.soinside.com 2019 - 2024. All rights reserved.