简体   繁体   English

如何从选定的下拉列表中获取另一个值

[英]How to get another value from the selected dropdownlist

I have project's class我有项目的课

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

then, it's displayed using dropdownlist然后,它使用下拉列表显示

@Html.DropDownListFor(model => model.Id,
    new SelectList(Model.Projects, "Id", "Name", Model.Id),
    "-- Select --",
    new { @class = "form-control" })

If I select a project, I can get the Id and Name, but how to get the description?如果我选择一个项目,我可以获得Id和Name,但如何获得描述?

<script>
    $(function () {
        $('#id').change(function () {
            alert('id = ' + $('#Id').val() + ', name = ' + $('#Id :selected').text() + ', description = ' + ???);
        });
    });
</script>

There are two ways有两种方式

  1. If list of projects are very large you will have to create API and use ajax to get a description.如果项目列表非常大,您将不得不创建 API 并使用 ajax 来获取描述。

  2. In javascript get list of project from model and find a description在javascript中从模型中获取项目列表并找到描述

<script>

var projects = @Html.Raw(Json.Encode(Model.Projects));
console.log(JSON.stringify(projects)); //only for test
 
$(function () {

        $('#id').change(function () {
 
    let id= $('#Id').val();
    let description = null;
     let name = null;
   
projects.forEach((item) => {
    if (item.Id === id) {
      name= item.Name;
      description= item.Description;
     break;
    }
});
    alert('id = ' + id + ', name = ' + name + ', description = ' + description);
        });
        
  }         
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从面板的下拉列表中获取所选值并进行计算? - How to get selected value from dropdownlist from a panel and make calculation? 如何基于使用ajax从另一个下拉列表中选择的值来更改下拉列表中的选项? - How do I change the options from a dropdownlist based on the selected value from another dropdownlist using ajax? 如何从视图中的 JQuery 下拉列表中获取所选值到 Controller - How to get selected value from JQuery Dropdownlist in View to Controller 如何从@Html.DropDownList 中获取选定的值 - How to get selected value from @Html.DropDownList 如何从分页的gridview中获取选定的值到下拉列表中 - how to get selected value from a paginated gridview into a dropdownlist 如何从代码将ListItem添加到DropDownList并获取所选值 - How to add ListItem to DropDownList from code and get the selected value 如何获取从数据库填充的下拉列表的选定值? - How do I get the selected value of a dropdownlist populated from a database? 如何从FormView中的下拉列表中获取项目的选定值? - How to get selected value of item from dropdownlist inside formview? 根据从另一个 DropDownList 中选择的值填充 DropDownList - Fill a DropDownList based on the selected value from another DropDownList 从DataList中的DropDownList获取选定值 - Get Selected Value from DropDownList inside a DataList
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM