Assign Attribute to @Html.DropdownList
Asked Answered
C

2

7

I want to assign some ID attribute name to my Dropdown list which is using data from the ViewBag as,

ViewBag.Group = new SelectList(group, "GroupId", "Name");

and in the View side I have used Razor syntax for showing the Dropdown as,

@Html.DropDownList("Group", "New", new { id="testID" } )

But I am getting the error on this line. Can I just assign ID of This Razor syntax? I know that the ID is generated with the Name "Playlist" But I am having 2 different dropdowns using same ViewBag. Because of that I have to assign different "ID" attribute value for them. How can it be done?

Clarence answered 30/5, 2013 at 5:33 Comment(0)
N
23

You should be using something like this

@Html.DropDownList("Group",null,new{@id="testID"});

because the data for the DropDownList comes from the ViewBag to name Group

Natalyanataniel answered 30/5, 2013 at 5:36 Comment(5)
can I assign some Default value in This Like I have assigned in My question as "New"??Clarence
@RahulRJ: yes it is an optionlabel that you can very well set.Natalyanataniel
But how can I set it Here if I want my default value as "New" in my DropdownClarence
Yes, how can I have the dropdownlist have an initial blank string at the beginning of the list?Nagging
Just set the option label as empty string or some content, it will be shown if none is selectedNatalyanataniel
E
10

Try it:

In controller

  ViewBag.EmployeeId = new SelectList(db.tb_employees, "id", "last_name");

In View

@Html.DropDownList("EmployeeId", (IEnumerable<SelectListItem>)ViewBag.EmployeeId,"Show All", new { @class = "form-control" })
Edva answered 25/3, 2014 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.