0

I have this code on controller side to initialise the drop down

        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem
        {Text = "All",
         Value = "All"

        });
        items.Add(new SelectListItem
        {
            Text = "val1",
            Value = "val1"
        });
        items.Add(new SelectListItem
        {
            Text = "val2",
            Value = "val2"
        });

        ViewData["DDLItems"] = items;

        // I have added this code because I am passing the selection back to this     action
        if (Activefilter == null){ Activefilter = "All" ;}

        ViewData["Activefilter"] = Activefilter;

On the view, I have this code

 <%= Html.DropDownList("ActiveFilter", (IEnumerable<SelectListItem>)ViewData["DDLItems"], new { onChange = "func(1)" })%>

for jquery , I have this

$(document).ready(function() {

                      $('#Activefilter').val(<%= ViewData["Activefilter"].ToString() %>);  
           }

so whenever , i change the value of the dropdown, the action is called as shown above. the viewdata["Actionfilter"] also takes the value selected by the user but when the control comes back to the view,

$('#Filter').val(<%= ViewData["Activefilter"].ToString() %>); 

in this line , it says the value "All" is undefined.

Everytime, the page reloads, I want the dropdown to retain the selected value. can you please help ?

tereško
  • 58,060
  • 25
  • 98
  • 150
user1005310
  • 737
  • 2
  • 12
  • 40

1 Answers1

0

You can use a SelectList() and in the constructor pass the selected item. Instead of using a list. remeber selected

why is the selected value not being taken in this example,

        List<SelectListItem> items = new List<SelectListItem>();

        items.Add(new SelectListItem
        {
            Text = "All",
            Value = "All"

        });
        items.Add(new SelectListItem
        {
            Text = "val1",
            Value = "val1",
        });
        items.Add(new SelectListItem
        {
            Text = "val2",
            Value = "val2","
        });


        string filter = "val1";
        ViewData["DDLItems1"] = new SelectList(items, "Text", "Value", filter);

on view , here is the code

<div>   @Html.DropDownList("FilterName", (SelectList)ViewData["DDLItems1"])</div>

That is razor syntax, switch to <% notation if you are not using razor

Community
  • 1
  • 1
Ryand.Johnson
  • 1,906
  • 2
  • 16
  • 22