【问题标题】:ASP.NET, MVC ListBoxFor Edit "The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed."ASP.NET,MVC ListBoxFor Edit “当允许多选时,参数‘表达式’必须计算为 IEnumerable。”
【发布时间】:2016-06-20 16:06:02
【问题描述】:

我收到一个我无法弄清楚的错误,甚至以前回答的问题也没有像我一样绑定 ListBox。

这是我在创建视图中使用 ListBox 的方式: ASP.NET MVC Return Comma Delimited String From From ListBoxFor To Controller

现在,当我进行编辑时,我收到此错误:

参数“表达式”必须在以下情况下计算为 IEnumerable 允许多选。

关于此代码:

 @Html.ListBoxFor(model => model.Mask_Concat, Enumerable.Empty<SelectListItem>(), new { @class = "chosen-container chosen-container-multi", @style = "width:300px" })

我已经尝试了所有我能想到的方法,将 ListBox 绑定到 ViewModel,仍然没有运气。

型号:

public string Mask_Concat { get; set; }

查看:

                <div class="fancy-form" id="mainMask">
                    @Html.LabelFor(model => model.Mask_Concat, "Mask(s)", new { @class = "control-label col-md-2" })
                    <div class="col-md-12">
                        @Html.ListBoxFor(model => model.Mask_Concat, Enumerable.Empty<SelectListItem>(), new { @class = "chosen-container chosen-container-multi", @style = "width:300px" })
                        @Html.ValidationMessageFor(model => model.Mask_Concat, "", new { @class = "text-danger" })
                    </div>
                </div>
                <input type="hidden" id="selectedMaskValues" name="selectedMaskValues" />

查看JS:

//join selected mask values
$("#Mask_Concat").chosen().change(function () {
    var $hidden = $("#selectedMaskValues");
    $hidden.val($(this).find('option:selected').map(function () {
        return $(this).val();
    }).get().join(","));
});

控制器:

public ActionResult Edit(string id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Chip_Master chipMaster = db.Chip_Master.Find(id);
    if (chipMaster == null)
    {
        return HttpNotFound();
    }
    ViewBag.Manufacturer = new SelectList(db.Chip_Master, "Mask_Concat", "Mask_Concat", chipMaster.Mask_Concat.Split(',').ToList());
    return View(chipMaster);
}

数据库: Mask_Concat 列:1234,5678,2345,7890

想法?需要更多信息?

【问题讨论】:

    标签: c# asp.net asp.net-mvc-4


    【解决方案1】:

    ListBoxFor 用于显示值的集合。您正在尝试将其映射到 single 字符串值。我会在您的模型中添加一个属性,将 Mask_Concat 拆分为一个数组并将 that 绑定到列表框:

    public string[] Mask_Concat_Values 
    { 
        get 
        {
            return Mask_Concat.Split(','); 
        }
        set 
        {
            Mask_Concat = string.Join(",",values);
        }
    }
    

    【讨论】:

    • 如何在模型中包含“值”?
    • 所以我只是将 Mask_Concat 作为值传递,现在我没有收到错误,但 ListFor 为空白且未填充值。
    猜你喜欢
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2013-10-10
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多