是否可以构建 CRUD 剃刀页面,实现用于显示/选择依赖实体的下拉列表?

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

我正在使用 VS 2022 for Mac 17.6。我当前的项目是使用 .NET 7.0 的 Razor WebApp 和使用 SQLite 的 EntityFramework。

这是我的数据模型:

public class Role
{
    public int Id { get; set; }
    public string? Description { get; set; }
}

public class EventTemplate
{
    public int Id { get; set; }
    public int Parent { get; set; }
    public int Predecessor { get; set; }
    public string? Identification { get; set; }
    public string? Description { get; set; }
    public Role? Role { get; set; }
}

根据我的理解,这段代码足以建立从EventTemplate到Role的1:1关系。我在吗?

现在我想要构建 CRUD 页面,其中“角色”以明文(描述)显示,或者用户可以从 DropDownList 中选择角色。我可以按照自己的方式自己编写此功能的代码,但根据我的理解,脚手架应该可以节省我的代码。

这可能吗?如果可能的话,是如何做到的?我是否必须更改我的 DataModel,或者如何更改?

提前致谢,托比亚斯

我尝试在 Pages/EventTemplates 文件夹中搭建脚手架。

VS 自动构建了常用页面,但“EventTemplate”实体的“Role”项既不显示也不可编辑。

c# entity-framework asp.net-core razor scaffolding
1个回答
0
投票

您需要在

EventTemplate
模型中手动创建外键属性,以便脚手架在创建页面中生成下拉列表。

public class EventTemplate
    {
        public int Id { get; set; }
        public int Parent { get; set; }
        public int Predecessor { get; set; }
        public string? Identification { get; set; }
        public string? Description { get; set; }
        public Role? Role { get; set; }
        public int RoleId { get; set; }
    }

生成的chtml代码

//......
<div class="form-group">
     <label asp-for="EventTemplate.RoleId" class="control-label"></label>
     <select asp-for="EventTemplate.RoleId" class ="form-control" asp-items="ViewBag.RoleId"></select>
</div>
//.......

但是在我看来,这个生成的下拉列表并不友好,所以你可以更改

ViewData["RoleId"] = new SelectList(_context.role, "Id", "Id");

ViewData["RoleId"] = new SelectList(_context.role, "Id", "Description");

Create.cshtml.cs

然后页面会显示如下:

© www.soinside.com 2019 - 2024. All rights reserved.