tags:

views:

156

answers:

0

Hi there

How do bind the SelectedValue in html.dropdownlist? BTW .. I am using the code as follow:

This is my repository:

public IEnumerable<SelectListItem> GetPlayers(Int64 SelectedPlayer)
        {
            var t = db.Players.ToList();
            IList<Player> player = db.Players.ToList(); 
            IEnumerable<SelectListItem> selectList = from c in player
                                                     select new SelectListItem
                                                     {
                                                         Text = c.FirstName + " " + c.LastName, 
                                                         Value = c.PlayerID.ToString() 
                                                     };
            return selectList;
        }

In the view:

<td><%= Html.DropDownList("Value", (IEnumerable<SelectListItem>)Model.Players )%>&nbsp;<%=Html.ActionLink("New", "Create", "Player")%></td>

BTW as you can see I am not using the selectedlist due to I have to combine the first and last name.

Thanks

Update:

public IEnumerable<SelectListItem> GetPlayers(Int64 id)
    {
        var s = from pr in db.PlayRounds
                where pr.PlayRoundID == id
                select new PlayRound
                    {
                        PlayerID = pr.PlayerID
                    };

        Int64 playerID;
        foreach(PlayRound var in s)
        {
             playerID = var.PlayerID;
        }

        IList<Player> player = db.Players.ToList();
        IEnumerable<SelectListItem> selectList = from c in player
                                                 select new SelectListItem 
                                                 {
                                                     Text = c.FirstName + " " + c.LastName, 
                                                     Value = c.PlayerID.ToString(),
                                                     Selected = (c.PlayerID == playerID)   
                                                 };
        return selectList;
    }

I've managed to change into this BUT I got the following error: Use of unassigned local variable 'playerID' (next to the line Selected = (c.PlayerID == playerID))

Any ideas?

related questions