1

I am trying to apply css class for asp.net mvc dropdown list. It works for editorfor case but not for dropdownlistfor case. What may be the missing part from my code?

Working css class for dropdown

@Html.EditorFor(model => model.role, new { htmlAttributes = new { @class = "form-control" } })

failing css class for drowdown

@Html.DropDownListFor(model => model.role, new SelectList((IEnumerable)ViewData["Roles"], "role1", "role1"), new { htmlAttributes = new { @class = "form-control" } })
2
  • 1
    new { @class = "form-control" } not new { htmlAttributes = new { @class = "form-control" } } Commented Mar 20, 2018 at 2:45
  • 1
    Just use new { @class = "form-control" } for DDLF CSS attribute, because EditorFor doesn't have htmlAttributes but DDLF has it. Commented Mar 20, 2018 at 2:46

1 Answer 1

3
//DropDownListFor: modelItem, selectList, optionLabel, htmlAttributes
//EditorFor: modelItem, additionalViewData

If you "right click" the code and peek definition (in Visual Studio) you'll see the definitions. So if you use this, it should work:

@Html.DropDownListFor(model => model.role, new SelectList((IEnumerable)ViewData["Roles"], "role1", "role1"), null, new { @class = "form-control" })
Sign up to request clarification or add additional context in comments.

2 Comments

,null with overload is really interesting. Thanks.
If you put in "--- please select ---" instead of null, you'll see it's purpose in the dropdown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.