Aditi
Aditi

Reputation: 1188

asp.net mvc listbox options are selected even though selected value is not defined

I am working with asp.net mvc. I have a listbox in my view. The options in this listbox are always selected on page load. I have not defined any selected value for this listbox. Can anyone tell me why this is happening?

Here is the code

          @{
               Dictionary<string, string> Options = new Dictionary<string, string>();
               ddlOptions.Add("1", "1");
               ddlOptions.Add("2", "2");
               ddlOptions.Add("3", "3n");
               ddlOptions.Add("4", "4");
           }
           <td>@Html.ListBoxFor(model => model.AvailableProducts, 
           new MultiSelectList(Options , "Key", "Value"), 
           new { size = "6" })

model.AvailableProducts is a list of strings:

        List<string> product = new List<string>();
        product.Add("1");
        product.Add("2");
        product.Add("3");
        product.Add("4");

Upvotes: 1

Views: 2043

Answers (1)

Andrei
Andrei

Reputation: 56688

Options are already selected because they are reflecting the state of your model. This line

@Html.ListBoxFor(model => model.AvailableProducts

tells ASP.NET MVC to bind the property model.AvailableProducts to the list box. Since this property contains all four options presented in the list, they all are selected by default. You can comment out code that fills this list and verify that none of the options are selected.

If you really want just a list box with options that will add specific parameter with name AvailableProducts to the request, you can use Html.ListBox:

@Html.ListBox("AvailableProducts", 
       new MultiSelectList(Options , "Key", "Value"), 
       new { size = "6" })

Upvotes: 1

Related Questions