0

In my controller I generated a SelectList that I pass to the dropdown helper:

  <%= Html.DropDownList("abc123", Model.SomeList) %>

I look at the querystring for a value, which is a ID.

I then loop through all the items in the SelectList and if it is equal to the ID, I do:

item.Selected = true;

The controller action then passes this SelectList to the view and then to the Html helper.

In debug mode I can see the value does get set to true, but the html renders without selecting the item.

What can the issue be?

2
  • In the view, temporarily comment out the dropdownlist, loop through Model.SomeList and confirm that the right item is "selected". Commented Jul 4, 2010 at 18:13
  • Could you show the controller action that performs the steps you described in your post? Commented Jul 4, 2010 at 19:13

2 Answers 2

2

I don't know what you are doing wrong as you've shown 0 code but this definitely works:

public ActionResult Index(int? id)
{
    var model = new SelectList(new[]
    {
        new { Id = 1, Name = "item 1" },
        new { Id = 2, Name = "item 2" },
    }, "Id", "Name", id);
    return View(model);
}

and in your view:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SelectList>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <%= Html.DropDownList("abc123", Model) %>

</asp:Content>

Now if you navigate to /home/index/1 the first item is selected, if you navigate to /home/index/2 the second item item selected.

Also if you are using ASP.NET MVC 2.0 I would recommend you the strongly typed DropDownListFor helper instead of DropDownList.

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

1 Comment

thanks it works when you pass the selectedValue in the constructor of selectList.
0

This seems to be a common MVC problem:

Html.DropDownListFor not behaving as expected ASP.net MVC

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.