在 ASP.NET Core MVC 中选择 Tag Helper [英] Select Tag Helper in ASP.NET Core MVC

查看:38
本文介绍了在 ASP.NET Core MVC 中选择 Tag Helper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关 ASP.NET Core 中的 select 标记助手的一些帮助.

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

我有一个员工列表,我试图将这些员工绑定到一个选择标签助手.我的员工在 List 中EmployeesList 和选定的值将进入 EmployeeId 属性.我的视图模型如下所示:

I have a list of employees that I'm trying to bind to a select tag helper. My employees are in a List<Employee> EmployeesList and selected value will go into EmployeeId property. My view model looks like this:

public class MyViewModel
{
   public int EmployeeId { get; set; }
   public string Comments { get; set; }
   public List<Employee> EmployeesList {get; set; }
}

我的员工类如下所示:

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

我的问题是如何告诉我的选择标签助手使用 Id 作为值,同时在下拉列表中显示 FullName?

My question is how do I tell my select tag helper to use the Id as the value while displaying FullName in the drop down list?

<select asp-for="EmployeeId" asp-items="???" />

我很感激这方面的帮助.谢谢.

I'd appreciate some help with this. Thanks.

推荐答案

使用 Select Tag 助手呈现 SELECT 元素

在您的 GET 操作中,创建视图模型的对象,加载 EmployeeList 集合属性并将其发送到视图.

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<Employee>
    {
        new Employee { Id = 1, FullName = "Shyju" },
        new Employee { Id = 2, FullName = "Bryan" }
    };
    return View(vm);
}

在您的创建视图中,从 EmployeeList 属性创建一个新的 SelectList 对象,并将其作为 asp-items 属性的值传递.

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
<form asp-controller="Home" asp-action="Create">

    <select asp-for="EmployeeId" 
            asp-items="@(new SelectList(Model.EmployeesList, nameof(Employee.Id), nameof(Employee.FullName)))">
        <option>Please select one</option>
    </select>

    <input type="submit"/>

</form>

以及你的 HttpPost action 方法来接受提交的表单数据.

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
}

如果您的视图模型有一个 List 作为下拉项的属性.

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

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

在你的 get 操作中,

And in your get action,

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

并且在视图中,您可以直接为 asp-items 使用 Employees 属性.

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

@model MyViewModel
<form asp-controller="Home" asp-action="Create">

    <label>Comments</label>
    <input type="text" asp-for="Comments"/>

    <label>Lucky Employee</label>
    <select asp-for="EmployeeId" asp-items="@Model.Employees" >
        <option>Please select one</option>
    </select>

    <input type="submit"/>

</form>

SelectListItem 类属于 Microsoft.AspNet.Mvc.Rendering 命名空间.

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

确保为 select 元素使用显式结束标记.如果您使用自关闭标签方法,标签助手将呈现一个空的 SELECT 元素!

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!

以下方法不起作用

<select asp-for="EmployeeId" asp-items="@Model.Employees" />

但这会奏效.

<select asp-for="EmployeeId" asp-items="@Model.Employees"></select>


使用实体框架从数据库表中获取数据

以上示例使用硬编码项作为选项.所以我想我会添加一些示例代码来使用实体框架获取数据,因为很多人都在使用它.


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.

假设您的 DbContext 对象有一个名为 Employees 的属性,它的类型为 DbSet,其中 Employee 实体类有一个IdName 这样的属性

Let's assume your DbContext object has a property called Employees, which is of type DbSet<Employee> 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; }
}

您可以使用 LINQ 查询来获取员工并使用 LINQ 表达式中的 Select 方法为每个员工创建一个 SelectListItem 对象列表.

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

假设 context 是您的数据库上下文对象.视图代码同上.

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

有些人更喜欢使用 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; }
}

现在在您的 GET 操作中,您可以使用 SelectList 构造函数来填充视图模型的 Employees 属性.确保您指定了 dataValueFielddataTextField 参数.您可以使用 nameof expression 来链接静态字段名称.

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. You can use a nameof expression to link the field names statically.

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

这里我调用 GetEmployees 方法来获取 Employee 对象的列表,每个对象都有一个 IdFirstName 属性,我使用这些我们创建的 SelectList 对象的 DataValueFieldDataTextField 属性.您可以将硬编码列表更改为从数据库表中读取数据的代码.

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.

视图代码将相同.

<select asp-for="EmployeeId" asp-items="@Model.Employees" >
    <option>Please select one</option>
</select>

从字符串列表中渲染一个 SELECT 元素.

有时您可能希望从字符串列表中呈现一个选择元素.在这种情况下,您可以使用 SelectList 构造函数,它只接受 IEnumerable

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

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

视图代码将相同.

有时,您可能希望将一个选项设置为 SELECT 元素中的默认选项(例如,在编辑屏幕中,您希望加载之前保存的选项值).为此,您只需将 EmployeeId 属性值设置为您要选择的选项的值.

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<SelectListItem>
    {
        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);
}

这将在页面呈现时选择 select 元素中的选项 Tom.

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

如果您想呈现多选下拉菜单,您只需将您用于视图中 asp-for 属性的视图模型属性更改为数组类型.

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<SelectListItem> Employees { set; get; }
}

这将使用 multiple 属性为 select 元素呈现 HTML 标记,这将允许用户选择多个选项.

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
<select id="EmployeeIds" multiple="multiple" name="EmployeeIds">
    <option>Please select one</option>
    <option value="1">Shyju</option>
    <option value="2">Sean</option>
</select>

在多选中设置选定的选项

与单选类似,将 EmployeeIds 属性值设置为您想要的值数组.

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<SelectListItem>
    {
        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);
}

这将在页面呈现时选择多选元素中的选项 Tom and Jerry.

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

如果您不喜欢保留集合类型属性来将选项列表传递给视图,您可以使用动态 ViewBag 来做到这一点.(这不是我个人推荐的方法,因为 viewbag 是动态的并且您的代码容易出现未捕获的拼写错误)

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 uncaught typo errors)

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

在视图中

<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
    <option>Please select one</option>
</select>

使用ViewBag传输项目列表并设置选中的选项

和上面一样.您所要做的就是将属性(您为其绑定下拉列表)的值设置为您要选择的选项的值.

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

在视图中

<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
    <option>Please select one</option>
</select>

分组项目

选择标签助手方法支持下拉列表中的分组选项.您所要做的就是在您的操作方法中指定每个 SelectListItemGroup 属性值.

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

视图代码没有变化.选择标签助手现在将呈现 2 optgroup 项目.

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

这篇关于在 ASP.NET Core MVC 中选择 Tag Helper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆