【问题标题】:Model state is not valid, when list has more than one item模型状态无效,当列表有多个项目时
【发布时间】:2020-08-02 13:36:09
【问题描述】:

我正在使用以下代码从 ui 中获取信息。 我使用 select2 作为 Combobox 让用户选择多个元素。

var saveObj = {
        
        DiscountRate: $('#discountRate').val(),
        State: $('#isActiveSelect2List').val() == 1 ? true : false,
        AuthorList: $('#authorSelect2List').val(),
        InterpreterList: $('#interpreterSelect2List').val(),
        TagList: $('#tagSelect2List').val()
    };

我将此数据保存为对象,然后使用 ajax 发布数据。但是,如果我为 select2 选择多个元素。我的控制器出现错误;

Error

但是,如果我只为 select2 选择一个元素,那没关系,模型状态为真。我不知道我错在哪里。 有什么建议吗?

这是我的数据模型;

    public List<int> AuthorList { get; set; }
    public List<int> InterpreterList { get; set; }
    public List<int> TagList { get; set; }

【问题讨论】:

    标签: javascript c# .net jquery-select2 modelstate


    【解决方案1】:

    在使用 ajax 发布数据时,您正在传递 select2 列表的逗号分隔值。 val() 以逗号分隔的字符串返回值,您需要将此字符串转换为数组,然后才能像这样发布数据:

    var authorSelectedList = [];
    var interpreterSelectedList= [];
    var tagSelectedList= [];
    if ($("#authorSelect2List").select2('data').length){
      $.each($("#authorSelect2List").select2('data'), function(key, item){
        authorSelectedList.push(item.text);
      });
    }
    if ($("#interpreterSelect2List").select2('data').length){
      $.each($("#interpreterSelect2List").select2('data'), function(key, item){
        interpreterSelectedList.push(item.text);
      });
    }
    if ($("#tagSelect2List").select2('data').length){
      $.each($("#tagSelect2List").select2('data'), function(key, item){
        tagSelectedList.push(item.text);
      });
    }
    var saveObj = {
        
        DiscountRate: $('#discountRate').val(),
        State: $('#isActiveSelect2List').val() == 1 ? true : false,
        AuthorList: authorSelectedList,
        InterpreterList: interpreterSelectedList,
        TagList: tagSelectedList
    };
    

    【讨论】:

    • 感谢您的回答,实际上 val() 正在返回一个这样的数组; "AuthorList":["3","52"],"InterpreterList":["10"],"TagList":["645"] ,两种解决方案的工作方式相同。我仍然收到错误,但如果我只为 select2 选择一个值,模型状态返回 true,如果我没有选择任何内容,它会再次给出相同的错误。
    • @AtakanÖzgürKartal 这是 ["3", "52"] 字符串数组吗?
    • 是的,我将数据作为 formdata 发布,因此将 select2 选项附加到 formdata 解决了我的问题。
    猜你喜欢
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    相关资源
    最近更新 更多