views:

54

answers:

2

Hi, I've got the following in my view:

<%= Html.DropDownList("Schema.MetaData.SourceTableName", new SelectList(Model.Schema.MetaData.SourceTableNames, Model.Schema.MetaData.SourceTableName), Model.SourceTablesOptionLabel)%>

SourceTableNames is of type List<string>

When I populate the model, I assign the value for SourceTableName using the following method on my view model:

public void SetDefaultSourceTable(string mostLikelyCandidate)
{
    Debug.Assert(this.Schema.MetaData.SourceTableNames.Contains(mostLikelyCandidate));
    this.Schema.MetaData.SourceTableName = mostLikelyCandidate;
}

(the Debug.Assert demonstrates that whatever I pass in is part of the SourceTableNames list)

Unfortunately, whatever I pass to that method, and even though all the properties are correct even when I put a breakpoint in the view itself, the first options is always selected

<SELECT id=Schema_MetaData_SourceTableName name=Schema.MetaData.SourceTableName>
  <OPTION selected>Table A</OPTION> 
  <OPTION>Table B</OPTION> 
  <OPTION>Table C</OPTION>
</SELECT> 

Any clue as to what I'm doing wrong?

A: 

Why don't you construct the selectlist in a custom viewmodel and just pull in from that in the view itself?

aka:

SelectList RolesList = new SelectList(roles, "RoleID", "RoleName", user.RoleID);

<%= Html.DropDownList("RoleID", Model.RolesList, "Select a Role...", new { @class = "required" }) %>

EDIT: roles is an IQueryable object, just a LINQ object that has roleid, rolename columns

where roleID is the key to associate the selected value, and user.roleid is the value to be selected.

this works in a few of my MVC applications

Jimmy
A: 

Hey, thanks for the comments and suggestions, and apologies for delayed feedback.

It seems that the DropDownList extension method overload taking in an optionLabel parameter is the culprit.

If I take that out (Model.SourceTablesOptionLabel), the correct item is selected as expected, regardless of how and where the SelectList is created and how I set its selected value.

I should probably have a look at the asp.net mvc source to see exactly what's going on and why this happens, but for now I'm on too tight a deadline to spend more time on this :)

Veli