如何从 table 填充 ASP.NET Core MVC 中的下拉列表?

How to populate a dropdownlist in ASP.NET Core MVC from table?

我最近需要重新开始使用 Visual Studio,但自从我在那里已经十多年了,不用说,我已经发生了很大的变化!我意识到有很多类似的问题,但我无法让其中任何一个发挥作用。如有任何帮助,我们将不胜感激!

情况是这样的:我有一个共享的搜索栏布局,目前正在对标题运行文本搜索。它需要一个类别下拉列表,该类别应该从 Category1 table.

编译

查看(Trees/Index):

<form asp-controller="Trees" asp-action="Index" method="get">
    <p>
        Category: @*select tag here*@
        Title: <input type="text" name="SearchString" />
        <input type="submit" value="Filter" />
    </p>
</form>

型号(Category1.cs):

public class Category1
{
    public int Id { get; set; }
    public string CategoryName { get; set; }
    public byte Active { get; set; }
}

控制器(TreesController.cs):

public async Task<IActionResult> Index(string searchString)
{
    var trees = from f in _context.Tree
                select f;

    if (!string.IsNullOrEmpty(searchString))
    {
        trees = trees.Where(s => s.Title.Contains(searchString));
    }

    return View(await trees.ToListAsync());
}

我已经删除了我尝试过的所有内容并恢复到基本搜索功能。如果您需要我不清楚的更多信息,请告诉我。提前致谢!

您可以像下面这样更改您的代码:

public async Task<IActionResult> Index(string searchString,int category1id)
{
    var trees = from f in _context.Tree
                select f;

    if (!string.IsNullOrEmpty(searchString))
    {
        trees = trees.Where(s => s.Title.Contains(searchString));
    }
    ViewData["Category1"] = new SelectList(_context.Category1.ToList(), "Id", "CategoryName");

    return View(await trees.ToListAsync());
}

查看:

<form asp-controller="Trees" asp-action="Index" method="get">
<p>
    Category: <select name="category1id" asp-items="ViewBag.Category1">
                <option>Category1</option>
            </select>
    Title: <input type="text" name="SearchString" />
    <input type="submit" value="Filter" />
</p>

更新:

您可以创建这样的函数:

public SelectList getCat1(ApplicationDbContext _context)
    {
        return (SelectList)(ViewData["Category1"] = new SelectList(_context.Category1.ToList(), "Id", "CategoryName"));
    }
public async Task<IActionResult> Index()
{
    getCat1(_context);
    return View();
}