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

I recently needed to start using Visual Studio again, but it has been over a decade since I’ve been in there and needless to say quite a bit has changed on me! I realize there are many similar questions, but I haven’t been able to get any of them to work. Any assistance would be greatly appreciated!

Here’s the situation: I have a a shared search bar layout which currently runs a text search on title. It needs a dropdown for category which should compile from the Category1 table.

View (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>

Model (Category1.cs):

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

Controller (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());
}

I’ve removed everything I tried and reverted back to the base search functionality. Please let me know if you need more information of if I have been unclear. Thank you in advance!

Answer

You can change your code like below:

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());
}

View:

<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>

Update:

You can create a function like this:

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();
}

Leave a Reply

Your email address will not be published. Required fields are marked *