asp.net MVC: How to add option to HTML.Dropdownlist
I have Html.DropDownList
element in View.
<%= Html.DropDownList("ID", (IEnumerable<SelectListItem>)ViewData["VItemID"])%>
In Controller:
ViewData["VItemID"] = new SelectList(_dataManager.myItems.getItems(), "ID", "ItemID");
I want to add option with text="----". I want do it in view layer开发者_Go百科.
I have done this with jquery, but I think it's not good idea using js code to solve problem.
What is the best way to do this?
You could use the proper helper overload:
<%= Html.DropDownList(
"ID",
(IEnumerable<SelectListItem>)ViewData["VItemID"],
"--- Please Select a Value ---")
%>
The best way is to do this in the Model and create a SelectItemList
with a default value. If you insist on doing it in the View then JQuery is as valid as a wrong approach as any other.
Customize your ViewData["VHouseTypes"] function.
public string GetDDLClients(int id)
{
string format = "<option value=\"{0}\" {2} >{1}</option>";
StringBuilder sb = new StringBuilder();
//string format = "<option value=\"{0}\">{1}</option>";
string formatSelected = "<option value=\"{0}\" selected=\"selected\">{1}</option>";
List<Highmark.BLL.Models.Client> client = Highmark.BLL.Services.ClientService.GetAll("", false);
sb.AppendFormat(formatSelected, "Select", "All Clients");
foreach (var item in client)
{
if (item.ClientID == id)
sb.AppendFormat(format, item.ClientID, item.CompanyName, "selected=\"selected\"");
else
sb.AppendFormat(format, item.ClientID, item.CompanyName, "");
}
return sb.ToString();
}
精彩评论