tags:

views:

33

answers:

3

Hello, 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.

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?

A: 

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();
    }
Amit
see this example.
Amit
+1  A: 

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.

Lazarus
@Lazarus, thanks.
loviji
+1  A: 

You could use the proper helper overload:

<%= Html.DropDownList(
    "ID", 
    (IEnumerable<SelectListItem>)ViewData["VItemID"], 
    "--- Please Select a Value ---")
%>
Darin Dimitrov
Thanks, as I understand "---Please ... ---" is html atributes. How to do if my ddl as <%= Html.DropDownList("ID"(IEnumerable<SelectListItem>)ViewData["VItemID"], new { @class = "fddl"") . How to combine to htmlAttribute? "ffdl" is css classname.%>
loviji
No it is not HTML attributes. It is `optionLabel`. To combine with HTML attributes use the other proper overload (http://msdn.microsoft.com/en-us/library/dd504967.aspx): `<%= Html.DropDownList("ID", (IEnumerable<SelectListItem>)ViewData["VItemID"], "--- Please Select a Value ---", new { @class = "fddl") %>`.
Darin Dimitrov