使用select2将空值添加到DropDownListFor

时间:2015-11-19 14:52:53

标签: jquery asp.net-mvc razor jquery-select2

我想显式添加一个空值,以便我可以将它与jQuery一起使用。

$('#empId').select2({
    placeholder: "Select report type",
    allowClear: true,
    width: "265px"
});

如何将其显示为选择的第一个(空)选项?

代码:

 @Html.DropDownListFor(m => m.EmpNameSelected,
    new SelectList(Model.ListOfEmployee, "", "", Model.EmpNameSelected),
     Model.EmpNameSelected, new { id = "empId" })

2 个答案:

答案 0 :(得分:0)

假设你有这个模型:

public class EmployeeModel
{
    public string EmpNameSelected { get; set; }
    public List<Employee> ListOfEmployee { get; set; }
}

public class Employee
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
}

这是控制器:

    public ActionResult TestEmployeeDropDownList()
    {
        var model = new EmployeeModel
        {
            ListOfEmployee = new List<Employee>
            {
                new Employee { EmployeeId = 1, EmployeeName = "John Doe" },
                new Employee { EmployeeId = 2, EmployeeName = "John Roe" },
                new Employee { EmployeeId = 3, EmployeeName = "Jane Doe" },
            }
        };
        return View(model);
    }

最后是视图:

@{
    var emptyEmployee = new MvcApplication.Models.Employee { EmployeeId = 0, EmployeeName = string.Empty };
    Model.ListOfEmployee.Insert(0, emptyEmployee);
}
@Html.DropDownListFor(m => m.EmpNameSelected, new SelectList(Model.ListOfEmployee, "EmployeeId", "EmployeeName", 0), new { id = "empId" })

答案 1 :(得分:0)

希望这会有助于其他人......

我真正需要的只是一行代码来插入新的empty value

@{Model.ListOfEmployee.Insert(0, "");}  //insert empty value

@Html.DropDownListFor(m => m.EmpNameSelected,
    new SelectList(Model.ListOfEmployee, "", "", Model.EmpNameSelected),
     Model.EmpNameSelected, new { id = "empId" })