【问题标题】:Set multiple SelectList values on PostBack在 PostBack 上设置多个 SelectList 值
【发布时间】:2016-09-01 11:38:32
【问题描述】:

我有一个包含多个选择列表的表单,我也使用引导选择选择器。

代码

型号

    [Display(Name = "SystemTyp")]
    [Required(ErrorMessage = "Vänligen välj typ")]
    public List<SelectListItem> SystemTypes { get; set; }

查看

    <div class="form-group">
        @Html.Label("SystemTyp", new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownList("SystemTypes",
           RegistrationHandlers.GetSystemtypes()
           ,
           new { @class = "form-control", @multiple = "multiple", @title = "---  Välj Systemtyp  ---" })
            @Html.ValidationMessageFor(model => model.SystemTypes, "", new { @class = "text-danger" })
        </div>
    </div>

发帖时:

每次我发布列表都是空的。 列表名称与模型属性名称匹配。

我错过了什么?

我有另一个列表,它是一个单一的选择,所以选择的值是一个简单的字符串,这工作正常,但上面让我头疼。

【问题讨论】:

  • 您的 SelectList 属性被命名为 SystemTypes 并且您显示的视图代码在任何地方都没有使用它。您所展示的只是一个DropDownList() 方法,它绑定到一个名为UserRole 的属性
  • 复制了错误的下拉列表,抱歉,检查编辑
  • SystemTypes 是您的SelectList。您不能绑定到SelectList。您的属性必须是(比如)IEnumerable&lt;int&gt; SystemTypes&lt;select&gt; 元素只回发一组简单值)
  • 不要使用DropDownList() - 使用ListBoxFor(m =&gt; m.SystemTypes, RegistrationHandlers.GetSystemtypes(), new { ... }) 这是生成&lt;select multiple&gt;的正确方法
  • @Stephen Muecke 最近你就像一个守护天使。谢谢m8

标签: c# asp.net-mvc asp.net-mvc-5 bootstrap-selectpicker


【解决方案1】:

您应该了解DropDownList 助手在html 标记中使用name="SystemTypes" 属性创建select 标记。

POST 中使用 UserRole 名称传递选定的值。

并且您不需要在 POST 上列出整个列表,您只需要选择的值,因此在您的 ViewModel 中创建 SystemTypeId 属性并将您的助手更改为:

 @Html.DropDownList("SystemTypeId", <-- note this
           RegistrationHandlers.GetSystemtypes()
           ,
           new { @class = "form-control", @multiple = "multiple", @title = "---  Välj Systemtyp  ---" })

然后您将在绑定模型中获得选定的值。

不要试图找回全部列表——你不需要它。

如果你需要选择多个你应该使用ListBoxhelper:

@Html.ListBox("SystemTypeIds", <-- note this
               RegistrationHandlers.GetSystemtypes()
               ,
               new { @class = "form-control", @title = "---  Välj Systemtyp  ---" })

SystemTypeIds 属性应为 ArrayIEnumerable&lt;int&gt;IList&lt;int&gt; 以绑定正确性。 (当然它不仅可以是int,还可以是stringbool 等。)

如果您正在寻找实现这一目标的最佳方法,我建议您使用强类型帮助器 - ListBoxFor:

@Html.ListBoxFor(x => x.SystemTypeIds
               ,RegistrationHandlers.GetSystemtypes()
               ,new { @class = "form-control", @title = "---  Välj Systemtyp  ---" })

【讨论】:

  • 对不起,在我的匆忙和沮丧中,我复制了错误的代码。检查编辑。我只想要选定的值
  • 您所描述的是,如果我只选择列表中的一项。但是当我选择多个时?
  • 我建议使用ListBoxFor() 方法,并将模型属性传递给它 - 重构时可以省去麻烦:)
  • @teovankot 然后也建议这样做。是的,我们来这里是为了帮助尝试解决 OP 的问题 - 但如果我们可以提出更好的做法来解决更深层次的问题,那么我们将全面加分!
  • ListBox()ListBoxFor() 添加 multlple 属性:)
猜你喜欢
  • 1970-01-01
  • 2014-11-09
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多