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

后端 未结 10 1683
情深已故
情深已故 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:22

    You can simply do this:

    @Html.DropDownList("PriorityID", null, new { @class="form-control"})
    
    0 讨论(0)
  • 2020-11-30 01:23

    Try This

     @Html.DropDownList("Id", null, new { @class = "ct-js-select ct-select-lg" })
    
    0 讨论(0)
  • 2020-11-30 01:24

    Simply Try this

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

    But if you want a default value or no option value then you must have to try this one, because String.Empty will select that no value for you which will work as a -select- as default option

    @Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, String.Empty, new { @class="dropdown" })
    
    0 讨论(0)
  • 2020-11-30 01:28

    You Can do it using jQuery

      $("select").addClass("form-control")
    

    here, Select is- html tag, Form-control is- class name

     @Html.DropDownList("SupplierId", "Select Supplier")
    

    and here, SupplierId is ViewBagList, Select Supplier is - Display Name

    0 讨论(0)
  • 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<SelectListItem>)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<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })
    
    0 讨论(0)
  • 2020-11-30 01:30

    There are some options in constructors look, if you don't have dropdownList and you wanna insert CSS class you can use like

    @Html.DropDownList("Country", null, "Choose-Category", new {@class="form-control"})
    

    in this case Country is the name of your dropdown, null is for you aren't passing any generic list from your controller "Choose-Category" is selected item and last one in CSS class if you don't wanna select any default option so simple replace "Choose-Category" with ""

    0 讨论(0)
提交回复
热议问题