Adding a css class to select using @Html.DropDownList()

后端 未结 10 1802
情深已故
情深已故 2020-11-30 01:13

I\'m building my first MVC application after years of doing webforms, and for some reason I am not able to make this work:

@Html.DropDownList(\"PriorityID\"         


        
10条回答
  •  青春惊慌失措
    2020-11-30 01:30

    Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.

    My view was one of the auto-generated ones, and contained this line of code:

    @Html.DropDownList("PriorityID", string.Empty)
    

    To add html attributes, I needed to do something like this:

    @Html.DropDownList("PriorityID", (IEnumerable)ViewBag.PriorityID, new { @class="dropdown" })
    

    Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...

    UPDATE:

    A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute

    @Html.DropDownListFor(x => x.PriorityID, (IEnumerable)ViewBag.PriorityID, new { @class = "dropdown" })
    

提交回复
热议问题