gpt4 book ai didi

razor - 如何使用没有 Controller 的 Razor Pages 填充下拉列表

转载 作者:行者123 更新时间:2023-12-02 00:31:15 24 4
gpt4 key购买 nike

我卡在这一部分了。当我进行搜索时,所有出现的都是 Controller 示例、viewbags 和 MVC 中的其他示例。

我正在尝试从数据库中填充下拉列表。到目前为止,这是我的代码

分类.cs

public class Category
{
[Key]
public int CategoryID { get; set}
public string CategoryName { get; set; }
}

Editor.cshtml.cs

public class Editor : PageModel
{
private readonly DatabaseContext _context;

public Editor(DatabaseContext databasecontext)
{
_context = databasecontext;
}

public void OnGet()
{
List<Category> categoryList = new List<Category>();
categoryList = (from Category in _context.Category select Category).ToList();
categoryList.Insert(0, new Category { CategoryID = 0, CategoryName = "Select" });
}
}

将下拉列表附加到我的 Razor View 页面的下一步是什么?

最佳答案

您可以使用 select tag helper还有 Razor 页面。

向您的页面模型添加 2 个其他公共(public)属性。一个用于显示选项项的项目集合,另一个用于存储/传递所选值。

public class Editor : PageModel
{
private readonly DatabaseContext _context;

public Editor(DatabaseContext databasecontext)
{
_context = databasecontext;
}

[BindProperty]
public int SelectedCategoryId { set; get; }

public List<SelectListItem> CategoryItems { set; get; }

public void OnGet()
{
CategoryItems = _context.Category
.Select(a=> new SelectListItem {
Value = a.CategoryId.ToString(),
Text = a.CategoryName })
.ToList();
}
}

现在在您的 View 中,使用 SELECT 标签助手。

@page
@model Editor
<form method="post">

<select asp-for="SelectedCategoryId" asp-items="@Model.CategoryItems">
<option>Select one</option>
</select>

<div>
<button type="submit" class="btn">SAve</button>
</div>

</form>

当用户提交表单时,您可以在页面模型的SelectedCategoryId 属性中读取选中的选项值。

public IActionResult OnPost()
{
var selectedCategoryId = this.SelectedCategoryId;
// to do : return something
}

关于razor - 如何使用没有 Controller 的 Razor Pages 填充下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com