I am creating a small mvc applicaiton and using DropDownListFor in it. Iam unable to set an id and class for that dropdownlist. Following is my DropdownListFor code in which i want to add Id and class. Timely help will be appreciated, thanks
@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--")
In order to set id
and class
of @Html.DropDownListFor
use below code :
@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--",new { @id="myid", @class="myclass" })
In order to set html attributes inside @Html.DropDownListFor
, you have to set 4th parameter of @Html.DropDownListFor
with new
keyword which will create a object
for htmlattributes
.
@Html.DropDownListFor
In html helpers If you want to add any html attribute you have to pass them as objects of htmlAttributes
type , Like explained by MSDN
public static MvcHtmlString DropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
Object htmlAttributes
)
Where htmlAttributes are
Type: System.Object
An object that contains the HTML attributes to set for the element
So as your question goes
@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--",new { @id="myid", @class="myclass" })
where new
keyword creates an object for htmlattributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With