问题
Database table
Language
- languageID (Primary key)
- language
- People
<%: Html.DropDownList("SprakID", new SelectList(ViewData["Sprak"] as IEnumerable, "languageID", "language", Model.languageID))%>
Goal:
Display the name of the language and what languageID in the DropDownList.
Problem:
Don't know how to display both language and languageID in the dropdownlist?
回答1:
Add a property to your Language class, for example
public string DataTextFieldLabel
{
get
{
return string.Format("{0} ({1})", language, languageId);
}
}
Now use it for the dataTextField
<%: Html.DropDownList("SprakID", new SelectList(ViewData["Sprak"] as IEnumerable, "languageID", "DataTextFieldLabel", Model.languageID))%>
回答2:
DropDownLists only have DataValueField and DataTextField properties, so one thing I can think of is to make a read-only property that combines both the name of the language and the ID, formatted the way you want it, and have the DropDownList use that for the DataTextField.
来源:https://stackoverflow.com/questions/4868627/display-two-properties-in-the-dropdownlist