从 select2 多选中获取值并将它们写入模型 属性

Get value from select2 multiselect and write them in a Model property

这是我的视图,其中有一个多选下拉列表:

    @model Model.FilterPresenter
    
                <div class="col-sm-1" style="display: inline-block">
                    <label class="individua-filter-name">Departement</label>
                    <div class="inputGroupContainer">
                        <div class="input-group">
                            @Html.DropDownListFor(model => Model.DepFilter.SelectedValue, Model.DepFilter.Values,
 new {id = "DepFilter", @multiple = "true"})
                        </div>
                    </div>
                </div>
    <script>
        $(document).ready(function () {
            multiselectFunction($('#DepFilter'), 90);
    
            $("button").css('text-shadow', 'none');
        });
    
        function multiselectFunction(element, size) {
            element.multiselect({
                disableIfEmpty: true,
                disabledText: ' -- ',
                maxHeight: 200,
                buttonWidth: '' + size + 'px',
                onChange: function () {
                    var selectEle = element.find("option:selected");
                    if (selectEle.length > 0) {
                        element.next().find("button").addClass('selectedFilter');
                    }
                    else {
                        element.next().find("button").removeClass('selectedFilter');
                    }
                },
                nonSelectedText: 'None',
                allSelectedText: 'All',
                numberDisplayed: 2,
                onSelectedText: 'Selected'
            });
        }
    
    </script>

这是 FilterPresenter class:

public class FilterPresenter
    {
        public FilterPresenter(List<SelectListItem> values, string selectedValue)
        {
            this.SelectedValue = selectedValue;
            this.Values = values;
        }

        public FilterPresenter()
        {
            this.SelectedValue = null;
            this.Values = new List<SelectListItem>();
        }

        public string SelectedValue { get; set; }

        public List<SelectListItem> Values { get; set; }

        public string[] multipleSelected { get; set; }
    }

在这里我看到可以恢复这样的值: https://jsfiddle.net/Shady_Alset/e5tg5kLr/

问题是是否可以检索所选元素的 ID,然后在我的 multipleSelected 中增强它们属性?

据我了解,您真正需要知道的是:

如何呈现 C# 对象以供以后在 js 代码中使用

  1. FilterPresenter中定义一个函数。此函数将 return 一个 Values:
  2. 的序列化字符串
// using Newtonsoft.Json;
// using Newtonsoft.Json.Serialization;

public string GetSerialized()
{
    return JsonConvert.SerializeObject(
        this.Values, 
        Formatting.None, 
        new JsonSerializerSettings {
            NullValueHandling = NullValueHandling.Ignore, 
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        }
    );
}
  1. 如果使用 @Html.DropDownListFor() 不是必须的,请不要使用它。您提供的示例 jsFiddle (https://jsfiddle.net/Shady_Alset/e5tg5kLr/) 是您的起点。如果必须使用 @Html.DropDownListFor(),请参阅第 1 点。 3.

在你的HTML中:

<input type="hidden" id="test" />

在您的 <script> 标签中:

var list = JSON.parse('@Html.Raw(Model.GetSerialized())'); // <-- this line is the key
  • Model.GetSerialized() returns 一个 C# 字符串(序列化值)。
  • Html.Raw()raw html.
  • 格式呈现字符串
  • 一对'使结果成为正确的js字符串。
  • JSON.parse()序列化的json字符串解析为js数组.

一旦找到将 C# 对象转换为 js 对象的方法,就可以在 js 代码中使用它。在此示例中,您需要将其作为 select2:

中的选项之一传递
$('#test').select2({
    data: list,
    multiple: true
});
  1. 如果必须使用 @Html.DropDownListFor() 呈现下拉列表,则需要获取下拉列表的选定 ID 并与 C# 对象创建的 js 对象相匹配。现在您可以回到第 2 点。并查看有关如何完成此操作的 js 代码。

This gist 包含说明上述要点的最小 MVC 示例。

祝你好运!