IEnumerable <selectlistitem>未显示数据库存储值</selectlistitem>

时间:2014-06-10 18:01:54

标签: c# razor

我有一个下拉列表,未在视图中显示默认值。调试后,我可以看到使用正确的值拉出默认值但它们没有显示。我将IEnumerable存储在我的ViewModel

实施例: DropDown 1应该显示True(即DB中的值),但显示第一个值&#34; Not Set&#34;

enter image description here

查看

@model IList<NavLiveWebInterface.ViewModel.Proc_Item_SKUViewModel>

    for (var i = 0; i < Model.Count(); i++)
    {
            <div class="editor-label">
                @Html.LabelFor(m => Model[i].Filterable)
            </div>
            <div class="editor-field">
                @Html.DropDownListFor(m => Model[i].Filterable,Model[i].TrueFalse)
            </div>
                @Html.ValidationMessageFor(m => Model[i].Filterable,"Please Select a Value")
    }

查看模型

public bool? Filterable { get; set; }
public IEnumerable<SelectListItem> TrueFalse
{
    get
    {
        return new[]
        {
            new SelectListItem { Value = "Not Set", Text = "Not Set" },
            new SelectListItem { Value = "True", Text = "True" },
            new SelectListItem { Value = "False", Text = "False" }
        };
    }
}

1 个答案:

答案 0 :(得分:2)

DropDownListFor不支持匹配索引表达式中的选定值。

您需要为每个条目创建一个SelectList,其中当前选定值已传递给它。

这将有效:

for (var i = 0; i < Model.Count(); i++)
{
    <div class="editor-label">
        @Html.LabelFor(m => Model[i].FilterableString)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(m => Model[i].Filterable, new SelectList(Model[i].TrueFalse, "Value", "Text", Model[i].Filterable));
    </div>
    @Html.ValidationMessageFor(m => Model[i].Filterable, "Please Select a Value")
}

您还在重复下拉列表的选项。仅从选项中创建的SelectList需要是唯一的(为了具有选定状态),因此您可以共享TrueFalse和{的单个数据列表{1}}选项并通过null提供(但不要忘记将其强制转换回ViewBag构造函数中的IEnumerable<SelectListItem>,否则会出错)

更新 - 共享列表:

您可以在ViewBag中创建单个共享列表,如此控制器代码:

SelectList

我使用了ViewBag.Filterable = new List<KeyValuePair<bool?, string>>() { new KeyValuePair<bool?, string>( null, "Not Set" ), new KeyValuePair<bool?, string>( true, "True" ), new KeyValuePair<bool?, string>( false, "False" ) }; ,因为这正是您为选项创建的内容。

并在视图中访问它:

KeyValuePair

最后一句话:

如果您没有使用索引项,则更简单的@Html.DropDownListFor(m => Model[i].Filterable, new SelectList((IEnumerable<KeyValuePair<bool?, string>>)ViewBag.Filterable, "Key", "Value", Model[i].Filterable)); 会自动将值绑定到@Html.DropDown("Filterable")(例如ViewModel),将下拉列表绑定到Model.Filterable同名的财产(例如ViewBag)。在较简单的情况下,这可以用于更短的代码。

相关问题