【问题标题】:How do I properly set the selected item in a SelectListItem?如何正确设置 SelectListItem 中的选定项目?
【发布时间】:2013-12-25 19:35:08
【问题描述】:

我构建了一个新的 SelectListItem。我可以填充选项,但它不会让我设置所选项目:

模型值

Model.Clients.ClientId = 1
Model.Clients.Name = "Company 1"
Model.Clients.ClientId = 2
Model.Clients.Name = "Company 2"
Model.Clients.ClientId = 3
Model.Clients.Name = "Company 3"
Model.Clients.ClientId = 4
Model.Clients.Name = "Company 4"
Model.Clients.ClientId = 5
Model.Clients.Name = "Company 5"

Model.User.Client.ClientId = 3

DropDownListFor

@Html.DropDownListFor(model => model.User.Client, Model.Clients.Select(x => new SelectListItem
{
    Text = x.Name,
    Value = x.ClientId.ToString(),
    Selected = x.ClientId == Model.User.Client.ClientId
    }).ToList(),
    new { @class = "form-control" }
)

下拉列表 HTML

<select class="form-control" id="User_Client" name="User.Client">
    <option value="1">Company 1</option>
    <option value="2">Company 2</option>
    <option value="3">Company 3</option>
    <option value="4">Company 4</option>
    <option value="5">Company 5</option>
</select>

我的代码应该将选项 3 设为所选项目,但事实并非如此。

【问题讨论】:

    标签: asp.net-mvc selectlistitem


    【解决方案1】:

    试试下面的代码:

    @Html.DropDownListFor(model => model.User.Client.ClientId, 
    new SelectList(Model.Clients,"ClientId","Name", Model.User.Client.ClientId), 
    new { @class = "form-control" })
    

    注意:不能为 DropDownList 绑定Client 类,需要使用ClientId 之类的属性。

    最好为选定的客户端添加另一个属性。如下:

    public class yourModel
    {
       public int selectedClientId {get;set;}
       //
    }
    
        @Html.DropDownListFor(model => model.selectedClientId, 
        new SelectList(Model.Clients,"ClientId","Name", Model.User.Client.ClientId), 
        new { @class = "form-control" })
    

    【讨论】:

    • 很好地抓住了类与财产的关系。我将枚举器的下拉列表从Model.User.Client 更改为Model.User.Client.ClientId,这解决了我的问题。
    【解决方案2】:

    试试下面的

     @Html.DropDownListFor(model  => model.User.Client,
     new SelectList(Model.Clients.ToList(), "ClientId", "Name", Model.User.Client.ClientId))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      相关资源
      最近更新 更多