DEV Community

Cover image for Select Tag Helper in ASP.NET Core MVC
Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

Select Tag Helper in ASP.NET Core MVC

In the article, we use Select Tag Helper in ASP.NET Core 2.1, I went online and saw many people also asking about how to use this, now I share with everyone how to use it.
Example : We already have a Categories table that alreadly has data available, and have create a Category.cs class in Models folder, you can the article previous:
Create Database using Code First in ASP.NET CORE 2.1
The first, you need add using Microsoft.AspNetCore.Mvc.Rendering in Controller file , Okay, go to Cotrollers folder, click right->add new->Controllers-> create ProductController.cs , after then add (Microsoft.AspNetCore.Mvc.Rendering)
Create Action CategoriesList() in ProductController.cs file

public ActionResult Create()
        {
            CategoriesList();
            CategoriesList2();
            return View();
        }

 private void CategoriesList(object selectCategory=null)
        {
            ViewBag.categories = new SelectList(_db.Categories.ToList(), "idCategory", "Name",selectCategory);
        }

private void CategoriesList2()
        {
            var data = _db.Categories.ToList();
            List<Category> list = new List<Category>();
            foreach(var item in data)
            {
                list.Add(new Category
                {
                    idCategory = item.idCategory,
                    Name = item.Name
                });
            }
            ViewBag.Categories2 = list;
        }
Enter fullscreen mode Exit fullscreen mode
  • _db.Categories.ToList(): read data from Categories table in Database
  • SelectList(): if you use SelectList(), you can insert library (using Microsoft.AspNetCore.Mvc.Rendering) in ProductController.cs file Okay, we need to Views/Product/ folder, create Create.cshtml file
<div class="form-group">
                    <label>Select Category</label>
                    <select asp-for="idCategory" asp-items="@ViewBag.Categories" class="form-control">
                        <option>Select one</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Select Category</label>
                    <select asp-for="idCategory" asp-items="@(new SelectList(ViewBag.Categories2,"idCategory","Name"))" class="form-control">
                        <option>Select one</option>
                    </select>
                </div>
Enter fullscreen mode Exit fullscreen mode

If you want to use it for Edit.cshtml, it is similar to Create.cshtml:
Add Action Edit(int id) to ProductController.cs file

public ActionResult Edit(int id)
{
      CategoriesList();
      CategoriesList2();
      return View(_db.Products.Find(id));
}
Enter fullscreen mode Exit fullscreen mode

The Article : Select Tag Helper in ASP.NET Core MVC

Top comments (0)