- 首先,在Blazor应用程序中创建您的实体模型。 例如,以下模型表示具有关联到LookUp表的Feed表:
public class Feed
{
public int FeedId { get; set; }
public string FeedName { get; set; }
public string FeedUrl { get; set; }
public int LookUpId { get; set; }
public virtual LookUp LookUp { get; set; }
}
public class LookUp
{
public int LookUpId { get; set; }
public string LookUpName { get; set; }
}
- 接下来,创建一个视图模型来处理下拉列表的数据。 在这个模型中,您将从数据库中检索LookUp表的数据并将其返回给您的视图以填充下拉列表。
public class FeedViewModel
{
private readonly ApplicationDbContext _context;
public FeedViewModel(ApplicationDbContext context)
{
_context = context;
}
public SelectList LookUpList =>
new SelectList(_context.LookUps, "LookUpId", "LookUpName");
public Feed FeedModel { get; set; }
}
- 在Controller中创建一个动作来处理视图模型。 在此方法中,您将检索Feed数据和LookUp数据,然后将它们存储在FeedViewModel中返回视图。
public async Task Create()
{
var viewModel = new FeedViewModel(_context);
return View(viewModel);
}
- 接下来,在您的视图中,将FeedViewModel传递到@model指令。 然后,在下拉列表中使用SelectList,并将其绑定到视图模型中的LookUpList属性。
@model FeedViewModel