【问题标题】:How do I populate a DropDown List using Razor Pages with No Controller如何使用没有控制器的 Razor 页面填充下拉列表
【发布时间】:2019-01-20 11:08:10
【问题描述】:

我被困在这一部分上。当我进行搜索时,所有出现的都是带有控制器、视图包和 MVC 中的其他示例的示例。

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

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

【问题讨论】:

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


    【解决方案1】:

    您也可以将select tag helper 与剃须刀页面一起使用。

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

    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
    }
    

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2020-06-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多