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

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

问题描述

我需要一些有关ASP.NET Core中选择标记帮助器的帮助.

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

我有一个要绑定到选择标签助手的员工列表.我的员工在List<Employee> 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; }
}

我的员工班级是这样的:

My employee class looks like this:

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

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

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

在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,"Id","FullName"))">
        <option>Please select one</option>
    </select>

    <input type="submit"/>

</form>

以及您的HttpPost操作方法来接受提交的表单数据.

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

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

在您采取行动时,

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

在视图中,您可以直接将Employees属性用于asp-items.

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命名空间.

确保为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>


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

以上示例对选项使用了硬编码的项目.因此,我想我会添加一些示例代码来使用Entity Framework来获取数据,因为很多人都在使用它.


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>,其中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参数.

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

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

分组项目

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

视图代码没有变化. select tag helper现在将在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中选择标签助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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