1

I am working with MVC and trying to show dropdownlist with some value selected.

 ViewData["History"] = new List<SelectListItem>() { new SelectListItem() { Text = "Never", Value = "-1" }, new SelectListItem() { Selected=true, Text = "7", Value = "7"},
                                            new SelectListItem(){ Text="14", Value="14"},new SelectListItem(){ Text="Forever", Value="999"}};

And in my View code

<p>
<label>History</label>
<%= System.Web.Mvc.Html.SelectExtensions.DropDownList(Html, "History", (IEnumerable<SelectListItem>)(ViewData["History"])) %>
</p>

Dropdown is rendered correctly, but selected value is not shown. First option is selected by default.

How to make selected option work ?

1 Answer 1

3

After writing this question I was looking for answers. But I found this post : DropDownList setting selected item in asp.net MVC

And then I tried making change as re-naming ViewData["History"] to ViewData["HistoryData"] and all of a sudden everything works as expected.

The name of select list and ViewData key should be different.

Sign up to request clarification or add additional context in comments.

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.