简体   繁体   中英

Select tag helper from database ASP.NET Core 3.1

Ok, I'm trying to do a proper dropdown in Core 3.1. In this example https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1#the-select-tag-helper Model has a new list with hardcoded values

public string Country { get; set; }

public List<SelectListItem> Countries { get; } = new List<SelectListItem>
{
   new SelectListItem { Value = "MX", Text = "Mexico" },
   new SelectListItem { Value = "CA", Text = "Canada" },
   new SelectListItem { Value = "US", Text = "USA"  },
};

I looked for examples where the list is coming from the database but they are very inconsistent. The only way I was able to do the dropdown list is with the ViewBag which is not advised.

I have two models. 1.

 public partial class Glossary
    {
        public int UniqueId { get; set; }
        public int Category { get; set; }
        public string DisplayText { get; set; }
    }
  1. which is my view model
 public partial class AdminUser
    {
        [Key]
        public int Id { get; set; }
        public string UserName { get; set; }
        public string UserLocation { get; set; }
        public string UserStatus { get; set; }
        //public IEnumerable<Glossary> Glossary { get; set; } //I used this for ViewBag 
        public List<SelectListItem> UserLocations { get; } = new List<SelectListItem>
        {
           according to the example my query should go here
        };      
    }

Here is my controller:

        public IActionResult Create()
        {
           // This is the ViewBag that worked with HTML helpers, but I'm trying to use tag-helpers.
            /*IEnumerable<SelectListItem> LocationsList = _context.Glossary.Where(x => x.Category == 1).Select(x => new SelectListItem
            {
                Value = x.UniqueId.ToString(),
                Text = x.DisplayText
            });
            ViewBag.LocationsList = LocationsList;
           */
            return View();
        }

All examples that found were hardcoded lists and nothing with getting it from the database. What is the proper way to get the data from the Glossary table through the view model with ViewBag? Any pointers are appreciated.

ALSO: When using this example: Select Tag Helper in ASP.NET Core MVC When I used

public SelectList Employees { set; get; }

I got error: InvalidOperationException: The entity type 'SelectListGroup' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.

Both of my tables have PK and adding [Key] to Glossary model didn't fix it.

If you'd like to retrieve data from db and populate a dropdown with retrieved data through a view model (or ViewBag), you can refer to following code snippet.

In AdminUser view model class, include these properties

public string Selected_Glossary { get; set; }
public List<SelectListItem> Glossary_List { get; set; }

In controller

public IActionResult Create(AdminUser model)
{
    var adminuser_model = new AdminUser
    {
        UserName="test"
        //for other properties
    };

    //retrieve data from Glossary table

    var items = _context.Glossary.Where(x => x.Category == 1).Select(x => new SelectListItem
    {
        Value = x.UniqueId.ToString(),
        Text = x.DisplayText
    }).ToList();


    //pass dropdown items through a view model
    adminuser_model.Glossary_List = items;

    ////pass dropdown items through ViewBag
    //ViewBag.Glossary_List = items;

    return View(adminuser_model);
}

In view page

@model AdminUser

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>
<form asp-controller="Home" asp-action="Create" method="post">
    <select asp-for="Selected_Glossary" asp-items="Model.Glossary_List"></select>
    @*populate it through ViewBag*@
    @*<select asp-for="Selected_Glossary" asp-items="ViewBag.Glossary_List"></select>*@
    <input type="submit" value="Submit" />
</form>

Test Result

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM