下拉列表剃须刀页面无控制器

时间:2018-08-13 16:49:10

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

我被困在这一部分。当我进行搜索时,所有出现的都是带有控制器,视图包的示例以及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" });
    }
}

将下拉列表附加到“剃刀视图”页面上的下一步是什么?

1 个答案:

答案 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
}
相关问题