MVC 4中的下拉列表未显示所选值

时间:2014-06-20 14:58:06

标签: c# asp.net asp.net-mvc

模型

public class LeadsVM
{
    public LeadsVM()
    {
        this.leadsList = new List<SingleLeadVM>();
    }

    public IList<SingleLeadVM> leadsList { get; set; }

    // For backup user and assign user 
    public IEnumerable<UserProfile> users { get; set; }

    public LeadDetailsVM leadDetailsVM { get; set; }

    [Display(Name = "Lead status")]
    public IEnumerable<LeadStatus> leadStatusList { get; set; }

}

查看

@for (int i = 0; i < Model.leadsList.Count; i++)
{    
@Html.DropDownListFor(model => Model.leadsList[i].assignedToUserId, new SelectList(Model.users, "UserId", "Email"), "Select user", new { data_val = false, data_users = Model.leadsList[i].leadId, @class = "usersList" })
}

我使用for循环而不是foreach的原因是我可以将数据集合提交回控制器。问题是,即使值可以从View传递到控制器,反之亦然,我无法在下拉列表中显示正确的值(我总是可以看到可选标签)。

解决方案

@Html.DropDownListFor(model => Model.leadsList[i].assignedToUserId, new SelectList(Model.users, "UserId", "Email", Model.leadsList[i].assignedToUserId), "Select user", new { data_val = false, data_users = Model.leadsList[i].leadId, @class = "usersList" })

1 个答案:

答案 0 :(得分:0)

修正了它。原来我可以使用SelectList构造函数的第4个参数。

@Html.DropDownListFor(model => Model.leadsList[i].assignedToUserId, new SelectList(Model.users, "UserId", "Email", Model.leadsList[i].assignedToUserId), "Select user", new { data_val = false, data_users = Model.leadsList[i].leadId, @class = "usersList" }) –  Adam Bielecki 9 mins ago