Asp.net-Mvc-4

如何設置 DropDownFor 的 id 和類 - asp.net mvc

  • September 26, 2014

我正在創建一個小型 mvc 應用程序並在其中使用 DropDownListFor。我無法為該下拉列表設置 id 和類。以下是我想在其中添加 Id 和類的 DropdownListFor 程式碼。及時幫助將不勝感激,謝謝

@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--")

**@Html.DropDownListFor**在 html 助手中如果你想添加任何 html 屬性,你必須將它們作為類型的對像傳遞,就像MSDNhtmlAttributes解釋的那樣

public static MvcHtmlString DropDownListFor<TModel, TProperty>(
   this HtmlHelper<TModel> htmlHelper,
   Expression<Func<TModel, TProperty>> expression,
   IEnumerable<SelectListItem> selectList,
   Object htmlAttributes
)

htmlAttributes 在哪裡

Type: System.Object
An object that contains the HTML attributes to set for the element

所以你的問題是

@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--",new { @id="myid", @class="myclass" })

wherenew關鍵字為 htmlattributes 創建一個對象

為了設置idclass使用@Html.DropDownListFor以下程式碼:

@Html.DropDownListFor(item => item.Student.StudentId, new SelectList(Model.StudentList, "StudentId", "FirstName"), "--Select--",new { @id="myid", @class="myclass" })

為了在裡面設置 html 屬性@Html.DropDownListFor,你必須設置@Html.DropDownListForwithnew關鍵字的第四個參數,這將創建一個objectfor htmlattributes

引用自:https://stackoverflow.com/questions/26054026