Select Tag Helper in ASP.NET Core MVC

前端 未结 6 2216
再見小時候
再見小時候 2020-11-22 04:35

I need some help with the select tag helper in ASP.NET Core.

I have a list of employees that I\'m trying to bind to a select tag helper. My employees are in a

6条回答
  •  无人共我
    2020-11-22 05:13

    Using the Select Tag helpers to render a SELECT element

    In your GET action, create an object of your view model, load the EmployeeList collection property and send that to the view.

    public IActionResult Create()
    {
        var vm = new MyViewModel();
        vm.EmployeesList = new List
        {
            new Employee { Id = 1, FullName = "Shyju" },
            new Employee { Id = 2, FullName = "Bryan" }
        };
        return View(vm);
    }
    

    And in your create view, create a new SelectList object from the EmployeeList property and pass that as value for the asp-items property.

    @model MyViewModel
    

    And your HttpPost action method to accept the submitted form data.

    [HttpPost]
    public IActionResult Create(MyViewModel model)
    {
       //  check model.EmployeeId 
       //  to do : Save and redirect
    }
    

    Or

    If your view model has a List as the property for your dropdown items.

    public class MyViewModel
    {
        public int EmployeeId { get; set; }
        public string Comments { get; set; }
        public List Employees { set; get; }
    }
    

    And in your get action,

    public IActionResult Create()
    {
        var vm = new MyViewModel();
        vm.Employees = new List
        {
            new SelectListItem {Text = "Shyju", Value = "1"},
            new SelectListItem {Text = "Sean", Value = "2"}
        };
        return View(vm);
    }
    

    And in the view, you can directly use the Employees property for the asp-items.

    @model MyViewModel
    

    The class SelectListItem belongs to Microsoft.AspNet.Mvc.Rendering namespace.

    Make sure you are using an explicit closing tag for the select element. If you use the self closing tag approach, the tag helper will render an empty SELECT element!

    The below approach will not work

    
    

    Getting data from your database table using entity framework

    The above examples are using hard coded items for the options. So i thought i will add some sample code to get data using Entity framework as a lot of people use that.

    Let's assume your DbContext object has a property called Employees, which is of type DbSet where the Employee entity class has an Id and Name property like this

    public class Employee
    {
       public int Id { set; get; }
       public string Name { set; get; }
    }
    

    You can use a LINQ query to get the employees and use the Select method in your LINQ expression to create a list of SelectListItem objects for each employee.

    public IActionResult Create()
    {
        var vm = new MyViewModel();
        vm.Employees = context.Employees
                              .Select(a => new SelectListItem() {  
                                  Value = a.Id.ToString(),
                                  Text = a.Name
                              })
                              .ToList();
        return View(vm);
    }
    

    Assuming context is your db context object. The view code is same as above.

    Using SelectList

    Some people prefer to use SelectList class to hold the items needed to render the options.

    public class MyViewModel
    {
        public int EmployeeId { get; set; }
        public SelectList Employees { set; get; }
    }
    

    Now in your GET action, you can use the SelectList constructor to populate the Employees property of the view model. Make sure you are specifying the dataValueField and dataTextField parameters.

    public IActionResult Create()
    {
        var vm = new MyViewModel();
        vm.Employees = new SelectList(GetEmployees(),"Id","FirstName");
        return View(vm);
    }
    public IEnumerable GetEmployees()
    {
        // hard coded list for demo. 
        // You may replace with real data from database to create Employee objects
        return new List
        {
            new Employee { Id = 1, FirstName = "Shyju" },
            new Employee { Id = 2, FirstName = "Bryan" }
        };
    }
    

    Here I am calling the GetEmployees method to get a list of Employee objects, each with an Id and FirstName property and I use those properties as DataValueField and DataTextField of the SelectList object we created. You can change the hardcoded list to a code which reads data from a database table.

    The view code will be same.

    
    

    Render a SELECT element from a list of strings.

    Sometimes you might want to render a select element from a list of strings. In that case, you can use the SelectList constructor which only takes IEnumerable

    var vm = new MyViewModel();
    var items = new List {"Monday", "Tuesday", "Wednesday"};
    vm.Employees = new SelectList(items);
    return View(vm);
    

    The view code will be same.

    Setting selected options

    Some times,you might want to set one option as the default option in the SELECT element (For example, in an edit screen, you want to load the previously saved option value). To do that, you may simply set the EmployeeId property value to the value of the option you want to be selected.

    public IActionResult Create()
    {
        var vm = new MyViewModel();
        vm.Employees = new List
        {
            new SelectListItem {Text = "Shyju", Value = "11"},
            new SelectListItem {Text = "Tom", Value = "12"},
            new SelectListItem {Text = "Jerry", Value = "13"}
        };
        vm.EmployeeId = 12;  // Here you set the value
        return View(vm);
    }
    

    This will select the option Tom in the select element when the page is rendered.

    Multi select dropdown

    If you want to render a multi select dropdown, you can simply change your view model property which you use for asp-for attribute in your view to an array type.

    public class MyViewModel
    {
        public int[] EmployeeIds { get; set; }
        public List Employees { set; get; }
    }
    

    This will render the HTML markup for the select element with the multiple attribute which will allow the user to select multiple options.

    @model MyViewModel
    
    

    Setting selected options in multi select

    Similar to single select, set the EmployeeIds property value to the an array of values you want.

    public IActionResult Create()
    {
        var vm = new MyViewModel();
        vm.Employees = new List
        {
            new SelectListItem {Text = "Shyju", Value = "11"},
            new SelectListItem {Text = "Tom", Value = "12"},
            new SelectListItem {Text = "Jerry", Value = "13"}
        };
        vm.EmployeeIds= new int[] { 12,13} ;  
        return View(vm);
    }
    

    This will select the option Tom and Jerry in the multi select element when the page is rendered.

    Using ViewBag to transfer the list of items

    If you do not prefer to keep a collection type property to pass the list of options to the view, you can use the dynamic ViewBag to do so.(This is not my personally recommended approach as viewbag is dynamic and your code is prone to uncatched typo errors)

    public IActionResult Create()
    {       
        ViewBag.Employees = new List
        {
            new SelectListItem {Text = "Shyju", Value = "1"},
            new SelectListItem {Text = "Sean", Value = "2"}
        };
        return View(new MyViewModel());
    }
    

    and in the view

    
    

    Using ViewBag to transfer the list of items and setting selected option

    It is same as above. All you have to do is, set the property (for which you are binding the dropdown for) value to the value of the option you want to be selected.

    public IActionResult Create()
    {       
        ViewBag.Employees = new List
        {
            new SelectListItem {Text = "Shyju", Value = "1"},
            new SelectListItem {Text = "Bryan", Value = "2"},
            new SelectListItem {Text = "Sean", Value = "3"}
        };
    
        vm.EmployeeId = 2;  // This will set Bryan as selected
    
        return View(new MyViewModel());
    }
    

    and in the view

    
    

    Grouping items

    The select tag helper method supports grouping options in a dropdown. All you have to do is, specify the Group property value of each SelectListItem in your action method.

    public IActionResult Create()
    {
        var vm = new MyViewModel();
    
        var group1 = new SelectListGroup { Name = "Dev Team" };
        var group2 = new SelectListGroup { Name = "QA Team" };
    
        var employeeList = new List()
        {
            new SelectListItem() { Value = "1", Text = "Shyju", Group = group1 },
            new SelectListItem() { Value = "2", Text = "Bryan", Group = group1 },
            new SelectListItem() { Value = "3", Text = "Kevin", Group = group2 },
            new SelectListItem() { Value = "4", Text = "Alex", Group = group2 }
        };
        vm.Employees = employeeList;
        return View(vm);
    }
    

    There is no change in the view code. the select tag helper will now render the options inside 2 optgroup items.

提交回复
热议问题