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

标签 razor asp.net-core asp.net-core-2.0

我卡在这一部分了。当我进行搜索时,所有出现的都是 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/

相关文章:

azure - 将 webapp 部署到 azure 密码

c# - 与 IMediatR 库一起使用时无法在类型化客户端中注入(inject) HttpClient

c# - 如何更改自定义字段(\Areas\Identity\Pages\Account\Manage\Index.cshtml.c)的值?

c# - 根据移动或桌面 HTML 和 CSS 更改图像

asp.net-mvc - MVC 3 Razor @model 与使用 @Model.pName 与 @Html.LabelFor(model => model.pName) 打印属性的模型

asp.net-mvc - mvc4 项目中的智能感知在 vs 2012 专业版中不起作用?

c# - VS Code 不为使用 net452 Framework 为 .NET Core 编译的项目加载 PDB

c# - 在 MySql.Data.EntityFrameworkCore 中找不到 Database SetInitializer

asp.net - 在 asp.net core 2 中,有没有办法部署未编译的 .cshtml 文件?

css - 在动态场景中管理 CSS float