HI WELCOME TO KANSIRIS

MULTIPLE WAYS TO GENERATE DROPDOWNLIST IN MVC USING HTML HELPERS

Leave a Comment
Implementation: Let’s generate a dropdownlist using various overloaded versions of DropDownList html helper. Actually there are various other ways to create and setup dropdownlist based on the requirement but I am listing a few of them. You can use any of these. And you can also try other overloaded methods of DropDownList helper.

In your view e.g. Index.cshtml view copy and paste the below mentioned code.

First Way

@Html.DropDownList("ddlDept"new List<SelectListItem>
{
    new SelectListItem { Text = "-- Select Department --", Value = "0", Selected=true},
    new SelectListItem { Text = "Accounts", Value = "1"},
    new SelectListItem { Text = "Sales", Value = "2"},
    new SelectListItem { Text = "HR", Value = "3"},
    new SelectListItem { Text = "IT", Value = "4"}
})


Second Way 

@{var listItems = new List<SelectListItem>
    {
          new SelectListItem { Text = "-- Select Department --", Value = "0" },
          new SelectListItem { Text = "Accounts", Value="1"  },
          new SelectListItem { Text = "Sales", Value="2" },
          new SelectListItem { Text = "HR", Value="3" },
          new SelectListItem { Text = "IT", Value="4"  }
    };
}
@Html.DropDownList("ddlDept"new SelectList(listItems, "Value""Text", 0))


Third Way

@{
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem
    {
        Text = "-- Select Department --",
        Value = "0",
        Selected = true
    });
    listItems.Add(new SelectListItem
    {
        Text = "Accounts",
        Value = "1"
    });
    listItems.Add(new SelectListItem
         {
             Text = "Sales",
             Value = "2"

         });
    listItems.Add(new SelectListItem
         {
             Text = "HR",
             Value = "3",
         });
    listItems.Add(new SelectListItem
    {
        Text = "IT",
        Value = "4"
    });
}

@Html.DropDownList("ddlDept", listItems)


Now run the application. You will get dropdownlist as shown in demo image above but generated using different methods.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.