如何使用 Razor 和 MVC 来使用带有多个选项的 select2

问题描述 投票:0回答:3

我正在尝试使用 Select2、Razor 和 MVC 框架创建一个多项选择列表。我的问题是控制器中接收数组输入的对象始终为空。前端如下所示:

<form class="form-horizontal" method="post" action="@Url.Action(MVC.Configurazione.Contatori.Edit())">
    <div class="form-group">
        <div class="col-lg-8">
            <select class="form-control attributoSelect2" name="attributiSelezionati" value="@Model.AttributiSelezionati">
                <option value="@Model.AttributiSelezionati" selected>@Model.AttributoDescrizione</option>
            </select>
        </div>
    </div>
</form>

操作方法“编辑”是从下拉列表中接收所选项目数组的控制器方法。

Javascript如下:

    $('.attributoSelect2').select2({
        placeholder: "Search attribute",
        multiple: true,
        allowClear: true,
        minimumInputLength: 0,
        ajax: {
            dataType: 'json',
            delay: 150,
            url: "@Url.Action(MVC.Configurazione.Attributi.SearchAttrubutes())",
            data: function (params) {
                return {
                    search: params.term
                };
            },
            processResults: function (data) {
                return {
                    results: data.map(function (item) {
                        return {
                            id: item.Id,
                            text: item.Description
                        };
                    })
                };
            }
        }
    });

最后,C# 控制器有一个期望从视图检索数据的对象并进行了定义:

public string[] AttributiSelezionati { get; set; }

而接收数据的HttpPost方法是:

[HttpPost]
public virtual ActionResult Edit(EditViewModel model) { }

有人可以让我深入了解我做错了什么以及我应该改变的地方以找到问题吗?

javascript c# asp.net asp.net-mvc jquery-select2
3个回答
0
投票

你的类名错误不是attributoSelect2而是attributesSelect2,我也经常犯这个错误。哈哈

 <select class="form-control attributoSelect2" name="attributiSelezionati" value="@Model.AttributiSelezionati">
                <option value="@Model.AttributiSelezionati" selected>@Model.AttributoDescrizione</option>
            </select>

0
投票

服务器收不到数据的原因有多种。首先,您需要更改您的选择代码,如下所示

@Html.DropDownList("attributiSelezionati", Model.AttributiSelezionati, new { @class = "form-control attributo select2" })

现在转到浏览器中的控制台并获取元素数据以确认您的代码在 HTML 和 JS 中正常工作

之后,您需要在控制器的操作方法中添加属性,如下所示:

[OverrideAuthorization] [HttpPost]
    

0
投票
您可以尝试以下在我们的一些项目中使用过的方法,没有任何问题:

查看:

@Html.DropDownListFor(m => m.StudentId, Enumerable.Empty<SelectListItem>(), "Select") $(document).ready(function () { var student = $("#StudentId"); //for Select2 Options: https://select2.github.io/options.html student.select2({ language: "tr",//don't forget to add language script (select2/js/i18n/tr.js) minimumInputLength: 0, //for listing all records > set 0 maximumInputLength: 20, //only allow terms up to 20 characters long multiple: false, placeholder: "Select", allowClear: true, tags: false, //prevent free text entry width: "100%", ajax: { url: '/Grade/StudentLookup', dataType: 'json', delay: 250, data: function (params) { return { query: params.term, //search term page: params.page }; }, processResults: function (data, page) { var newData = []; $.each(data, function (index, item) { newData.push({ //id part present in data id: item.Id, //string to be displayed text: item.Name + " " + item.Surname }); }); return { results: newData }; }, cache: true }, escapeMarkup: function (markup) { return markup; } }); //You can simply listen to the select2:select event to get the selected item student.on('select2:select', onSelect) function onSelect(evt) { console.log($(this).val()); } //Event example for close event student.on('select2:close', onClose) function onClose(evt) { console.log('Closed…'); } });


控制器:

public ActionResult StudentLookup(string query) { var students = repository.Students.Select(m => new StudentViewModel { Id = m.Id, Name = m.Name, Surname = m.Surname }) //if "query" is null, get all records .Where(m => string.IsNullOrEmpty(query) || m.Name.StartsWith(query)) .OrderBy(m => m.Name); return Json(students, JsonRequestBehavior.AllowGet); }

希望这有帮助...

更新:

下拉选项组:

<select> <optgroup label="Group Name"> <option>Nested option</option> </optgroup> </select>

有关更多信息,请查看

https://select2.org/options

© www.soinside.com 2019 - 2024. All rights reserved.