【问题标题】:MVC .NET DropdownList selected valueMVC .NET DropdownList 选定值
【发布时间】:2015-06-21 02:18:02
【问题描述】:

我的模型的下拉列表有问题。我无法设置默认选择值。这是我的代码。 选择列表定义:

var productGroups = db.sl_GrupaKh.AsNoTracking()
        .Where(g => g.kh__Kontrahent.Any())
        .Select(n => new {n.grk_Id, n.grk_Nazwa })
        .OrderBy(n => n.grk_Nazwa).ToList();
        productGroups.Add(new { grk_Id = 0, grk_Nazwa = "(" + Resources.Resources.NoneLabel + ")" });
        productGroups.Add(new { grk_Id = -1, grk_Nazwa = "(" + Resources.Resources.AnyLabel + ")" });

        var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected);
        SelectList selectList = new SelectList(productGroups,"grk_Id","grk_Nazwa",selected);

grk_Id - int 类型,grk_Nazwa-string 类型,selected - int 类型 我已经看到 selected 匹配选项值之一。

现在查看代码:

    @Html.DropDownListFor(m => m.customerMenu, Model.customerMenu,
new  {@class="myClass" })

然后输出:

<select class="dasdas" id="customerMenu" name="customerMenu">
<option value="2">Drogerie</option>
<option value="3">Fabryki</option>
<option value="4">Hurtownie</option>
<option value="5">Importerzy</option>
<option value="1">Podstawowa</option>
<option value="6">Sklepy</option>
<option value="0">(brak)</option>
<option value="-1">(dowolna)</option>
</select>

我期待任何帮助。谢谢你:)

【问题讨论】:

    标签: c# .net razor model-view-controller


    【解决方案1】:

    您可以使用SelectList 而不是SelectList,您只需从中获胜,不再需要硬编码字符串,并且您可以确定Selected 项目是true

    var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected);
    List<SelectListItem> selectList = productGroups.Select(c => new SelectListItem
            {
                Text = c.grk_Nazwa,
                Value = c.grk_Id,
                Selected = selectedItem != null && selectedItem.grk_Id == c.grk_Id
            });
    

    注意:如果您无法更改SelectList,请尝试此SO answer,这将帮助您从List&lt;SelectListItem&gt; 转换为SelectList

    【讨论】:

    • 我会试试的。谢谢。 :)
    【解决方案2】:

    我认为这是一个错误

    SelectList selectList = new SelectList(productGroups,"grk_Id","grk_Nazwa",selected);
    

    这个

    var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected);
    

    必须改成这个

    var selectedItem = productGroups.SingleOrDefault(x=>x.grk_Id==selected).grk_Id;
    

    也许使用 NullReferenceCheck。

    【讨论】:

    • @adricadar 解决方案好多了。
    • 但我使用 selectedItem 只是为了查看在调试时选择的参数是否指向 null。如您所见: SelectList selectList = new SelectList(productGroups,"grk_Id","grk_Nazwa",selected);有选择的参数未选择项
    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    相关资源
    最近更新 更多