0

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?

3 Answers 3

3

You could use the proper helper overload:

<%= Html.DropDownList(
    "ID", 
    (IEnumerable<SelectListItem>)ViewData["VItemID"], 
    "--- Please Select a Value ---")
%>
Sign up to request clarification or add additional context in comments.

2 Comments

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. %>
No it is not HTML attributes. It is optionLabel. To combine with HTML attributes use the other proper overload (msdn.microsoft.com/en-us/library/dd504967.aspx): <%= Html.DropDownList("ID", (IEnumerable<SelectListItem>)ViewData["VItemID"], "--- Please Select a Value ---", new { @class = "fddl") %>.
1

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.

Comments

0

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();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.