2

I want to add an empty value explicitly so that I can use that with jQuery.

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

How can I make it appear as the first (empty) option of the select?

Code:

 @Html.DropDownListFor(m => m.EmpNameSelected,
    new SelectList(Model.ListOfEmployee, "", "", Model.EmpNameSelected),
     Model.EmpNameSelected, new { id = "empId" })
Erik Gillespie
  • 3,929
  • 2
  • 31
  • 48
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406
  • 2
    Possible duplicate of [DropdownListFor default value](http://stackoverflow.com/questions/7229626/dropdownlistfor-default-value) – markpsmith Nov 19 '15 at 14:56

2 Answers2

0

Suppose you have this model:

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; }
}

Here is the controller:

    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);
    }

Finally the View:

@{
    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" })
user449689
  • 3,142
  • 4
  • 19
  • 37
0

Hope this will help others...

What I really needed is just one line of code to insert a new 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" })
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406