多选所选下拉列表 - 想要设置值

时间:2013-12-10 14:32:20

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

请告诉我如何在所选的多选下拉列表中设置所选值。我已尝试过网上所有可用的东西,但没有任何工作。

我的观点是

@Html.DropDownListFor(
    model => model.SelectedSkills, 
    new SelectList(
        Model.SkillList, 
        "Value", 
        "Text", 
        Model.SelectedSkills
    ), 
    new { 
        @class = "chosen", 
        id = "ddlSkill",
        name="ddlPersonSkill", 
        @tabindex = "4", 
        multiple = "true"
    }
)

@Html.HiddenFor(
    model => model.SelectedSkills, 
    new { id = "hdnPersonSkill" }
)

现在在页面加载中我需要显示所选的值:

var personskill = $("#hdnPersonSkill").val(); 
$('#ddlSkill option:nth-child(3)').attr('selected', 'selected');
$('#ddlSkill').trigger('liszt:updated');

但上面的代码无效

1 个答案:

答案 0 :(得分:0)

CHHTML:

@Html.ListBoxFor(
        model => model.SelectedSkills,
        new SelectList(
        Model.SkillList,
        "Value",
        "Text",
        Model.SelectedSkills
        ),
        new
        {
            @class = "chosen",
            id = "ddlSkill",
            name = "ddlPersonSkill",
            @tabindex = "4",
            multiple = "true"
        }
        )

Javascript显示所有选中的内容:

$(document).ready(function () {
        var conceptName = $('#ddlSkill').find(":selected").text();
        alert(conceptName);
    });

模型只是例如:

public string[] SelectedSkills { get; set; }
    public IEnumerable<SelectListItem> SkillList { get; set; }

    public MyModel()
    {
        SkillList = new List<SelectListItem>();
        ((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 1", Value = "1" });
        ((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 2", Value = "2" });
        ((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 3", Value = "3" });
        ((List<SelectListItem>)SkillList).Add(new SelectListItem { Text = "Skill 4", Value = "4" });

        SelectedSkills = new string[3];
        SelectedSkills[0] = "1";
        SelectedSkills[1] = "2";
        SelectedSkills[2] = "3";
    }