gpt4 book ai didi

asp.net-mvc - 将数组绑定(bind)到多个 DropDownListFor

转载 作者:行者123 更新时间:2023-12-02 02:06:36 25 4
gpt4 key购买 nike

我有一个场景,我想从复选框列表中选择 3 个项目。这工作正常,但如果复选框列表变长,页面看起来很笨重。所以我想将其更改为 3 个下拉列表。所以页面小了很多,但没有一个下拉列表支持所选值。

所以我尝试了这样的代码

@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 0 ? Model.CheckedLarcenyTypes[0] : null as Int32?), String.Empty, new { id = "Larceny1" })
@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 1 ? Model.CheckedLarcenyTypes[1] : null as Int32?), String.Empty, new { id = "Larceny2" })
@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 2 ? Model.CheckedLarcenyTypes[2] : null as Int32?), String.Empty, new { id = "Larceny3" })

现在下拉菜单已正确创建,正确的值已绑定(bind),在 POST 上我看到值被发送回 View 模型。

我无法让选择值显示在下拉列表中。重新加载页面后,下拉菜单仍然是空白的。

我在这里做错了什么?这可能吗?

最佳答案

您的问题与描述的内容有关here .

Reading the Selection

If you are using the same model to accept input from the edit view during a postback, you might think the default model binder will repopulate the Albums collection with all the album information and set the selected album. Unfortunately - the web doesn’t work this way and the Albums collection will be empty.

所以你必须有一个像这样的 ViewModel:

public class LarcenyViewModel
{
public int CheckedLarcenyType1 { get; set; }
public int CheckedLarcenyType2 { get; set; }
public int CheckedLarcenyType3 { get; set; }
public IEnumerable<SelectListItem> LarcenyTypes { get; set; }
}

像这样填充 ViewModel:

LarcenyViewModel larcenyViewModel = new LarcenyViewModel();

// Use a database, enum or whatever to get the LarcenyTypes... :)
larcenyViewModel.LarcenyTypes = new SelectList(
database.FindAllLarcenyTypes(), "LarcenyId", "Name");

查看代码:

@Html.DropDownListFor(model => model.CheckedLarcenyType1, Model.LarcenyTypes, String.Empty, new { id = "Larceny1" })
@Html.DropDownListFor(model => model.CheckedLarcenyType2, Model.LarcenyTypes, String.Empty, new { id = "Larceny2" })
@Html.DropDownListFor(model => model.CheckedLarcenyType3, Model.LarcenyTypes, String.Empty, new { id = "Larceny3" })

关于asp.net-mvc - 将数组绑定(bind)到多个 DropDownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14737180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com