如何使用没有控制器的 Razor Pages 填充下拉列表

How do I populate a DropDown List using Razor Pages with No Controller

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

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

Category.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 视图页面的下一步是什么?

您也可以将 与剃刀页面一起使用。

向您的页面模型添加 2 个其他 public 属性。一个用于显示选项项的项目集合,另一个用于 storing/passing 所选值。

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();
    }
}

现在在您的视图中,使用 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
}