【问题标题】:How to get an extra parameter value in Select2 via jQuery?如何通过 jQuery 在 Select2 中获取额外的参数值?
【发布时间】:2016-11-17 08:49:44
【问题描述】:

我将一个额外的属性绑定到 Select2 ddl 并希望通过 jQuery 检索此属性值(Key),如下所示:

控制器:

public ActionResult GetProjects()
{
    var projects = repository.Projects.Select(m => new ProjectViewModel
    {
        Id = m.Id,
        Name = m.Name,
        Key = m.Key //Extra parameter that I want to retrieve using jQuery                
    })
    return Json(projects, JsonRequestBehavior.AllowGet);
}

我成功填充了 ddl 并尝试获取除 Name 和 Id onChange 之外的 Key 值,但不知道如何获取它:

查看:

<input type="hidden" id="key" name="Key" value=0 /> 

//I fill the ddl without no problem via Select2 and there is no need to post its code for brevity
@Html.DropDownListFor(m => m.ProjectId, Enumerable.Empty<SelectListItem>(), "Select")

$('#ProjectId').change(function (e) {
        projectId = $(this).val(); // I can get the selected ProjectId value
        debugger;

        //!!! But cannot get the Key value
        var key = $('#ProjectId').select2('data').Key;
}

有什么想法吗?

这是 Select2 的渲染 HTML:

<select class="select2-hidden-accessible" data-val="true" data-val-number="The field Proje must be a number." data-val-required="Req" id="ProjectId" name="ProjectId" 
tabindex="-1" aria-hidden="true"><option value="">Select</option>
<option value="1">Project A</option></select>

<span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-autocomplete="list" aria-haspopup="true" 
aria-expanded="false" tabindex="0" aria-labelledby="select2-ProjectId-container"><span class="select2-selection__rendered" id="select2-ProjectId-container" 
title="Project A"><span class="select2-selection__clear">×</span>Project A</span><span class="select2-selection__arrow" role="presentation">
<b role="presentation"></b></span></span></span>

【问题讨论】:

  • 你能显示为 select2 渲染的 html
  • @Mir 已发布到问题。
  • 抱歉,我在您的选择选项中没有看到任何关键属性

标签: javascript jquery asp.net-mvc jquery-select2 select2


【解决方案1】:

这里是问题的解决方案:

<input type="hidden" id="projectPKey" name="ProjectPKey" value=0 /> 

@Html.DropDownListFor(m => m.ProjectId, Enumerable.Empty<SelectListItem>(), "Select" )

projectId.select2({
    //code removed for brevity
    processResults: function (data, page) {
    var newData = [];
    $.each(data, function (index, item) {
        newData.push({            
            id: item.Id, //id part present in data             
            text: item.Description, //string to be displayed
            key: item.Key //extra parameter(s)
        });
    });
});


var pkey = $('#ProjectId').find(':selected').data().data.key;
$('#projectPKey').val(pkey);
console.log(pkey);

【讨论】:

    猜你喜欢
    • 2012-10-05
    • 2023-04-02
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多