views:

2686

answers:

3

My page view currently has a dropdownlist on it that is getting bound to a collection from the controller. This is working fine, However I want to insert an item to the top of the dropdownlist that is not in my collection e.g the list currently gets the following items

Open
Closed

I want to add a third option of "All" but I don't want to add this option to my database. In Webforms I would have just bound the control then inserted another item however it seems this is not possible with MVC, am I right in thinking I will need to add some Javascript to the view to add this new item once the dropdownlist has been bound?

Thanks

A: 

Simple

you can make it as you wish in controller.

and pass it in viewdata.

other option is directly in view page.

<%= Html.DropDownList("DropDown","all" )%>

But you can add only one option..

Make sure you are not storing added options in ur db, right? so before you save it, check option value in action and apply your logic.

Vikas
The value for this is the empty string and as such I don't think it will get posted back. If you want a value like "all" instead of "none", you'll need to adjust the list on the server side (or with Javascript).
tvanfosson
+1  A: 

No. Construct your data as a list of SelectListItems and prepend in the controller.

   var list = db.Table
                .Select( t => new SelectListItem
                              { 
                                  Key = t.ID.ToString(),
                                  Value = t.Name
                              } )
                .ToList();
   list.Insert( 0, new SelectListItem { Key = "-1", Value = "All" } );

   ViewData["TableSelect"] = list;

On the view side:

   <%= Html.DropDownList( "TableID",
                          (IEnumerable<SelectListItem>)ViewData["TableSelect"] ) %>
tvanfosson
We can also use <%= Html.DropDownList("TableSelect" )%> directly if the same name contains in viewdata.
Vikas
Ultimately he has to check it at server side because GavD Don't want "all" to be in DB
Vikas
I cant get list.Insert to work its implying there is no insert method
Gavin Draper
Because list is of type Interface ( IQueryable) and there is no way to add new item in it, unless you merge two Interface.
Vikas
Sorry -- missed a step. After selecting the new SelectListItems you need to add a ToList() to make it into List<SelectListItem> instead of IEnumerable<SelectListItem>. Then you can add to it. I've updated.
tvanfosson
A: 

Have you tried adding the AppendDataBoundItems="True"? See below for an example;

 <asp:DropDownList ID="DDL_Name" runat="server" DataSourceID="Name" 
            DataTextField="Name" DataValueField="name" AutoPostBack="True" 
            AppendDataBoundItems="True">
        <asp:ListItem Value="">All</asp:ListItem>
    </asp:DropDownList>
HighlyEvolved
This question is about MVC - Not WebForms
mlarsen