Razor 无控制器的刮胡刀页面下拉列表
我被困在这一部分。当我进行搜索时,只会出现控制器示例、viewbags和MVC中的其他示例 我正在尝试从数据库填充下拉列表。这是到目前为止我的代码 C类Razor 无控制器的刮胡刀页面下拉列表,razor,asp.net-core,asp.net-core-2.0,Razor,Asp.net Core,Asp.net Core 2.0,我被困在这一部分。当我进行搜索时,只会出现控制器示例、viewbags和MVC中的其他示例 我正在尝试从数据库填充下拉列表。这是到目前为止我的代码 C类 public class Category { [Key] public int CategoryID { get; set} public string CategoryName { get; set; } } } Editor.cshtml.cs public class Editor : PageModel {
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" });
}
}
公共类编辑器:页面模型
{
私有只读数据库上下文\u上下文;
公共编辑器(DatabaseContext DatabaseContext)
{
_上下文=数据库上下文;
}
公共互联网
{
List categoryList=新列表();
categoryList=(从_context.Category中的Category选择Category).ToList();
Insert(0,新类别{CategoryID=0,CategoryName=“Select”});
}
}
将dropdownlist附加到我的Razor视图页面的下一步是什么?您也可以将与Razor页面一起使用
向页面模型添加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();
}
}
您也可以使用剃须刀页面
向页面模型添加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();
}
}
谢谢你的帮助。
public IActionResult OnPost()
{
var selectedCategoryId = this.SelectedCategoryId;
// to do : return something
}