DJ Dev DJ Dev - 11 days ago 6
C# Question

DropDownListFor not preselecting value

I'm building an MVC web application and am about to run my head through the wall, there's a dozen topics on this already and all have accepted solutions that do not work for me. There's probably something really stupid and simple I'm forgetting/not seeing, but can't seem to work it out.
Please don't hate me for naming; I'm continuing a project started by someone else.

I have the following line in my ManageDetail.cshtml:

@Html.DropDownListFor(m => m.ChecklistWaarde.SoortID, Model.ChecklistOptionsOptions, "Choose a value", new { @class = "form-control" })


This builds a selectbox based on property Model.ChecklistWaarde.SoortID, which is an integer. The next parameter passed is a SelectList from the model that is generated by the following very simple helper function that does a DB lookup in a 2ndary database (unfortunately), it receives the parameter SoortID as well to set a preselect value:

public SelectList GetChecklistOptions(int selectedId = -1)
{
var soorten = new List<SelectListItem>();
try
{
using (var connection = new SqlConnection(mssqlConnectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "Select Naam, ID From ChecklistSoorten";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var id = reader["ID"] as int?;
if (id.HasValue)
{
soorten.Add(new SelectListItem { Text = reader["Naam"] as string, Value = id.Value.ToString(), Selected = id.Value.Equals(selectedId) });
}
}
}
}
catch (Exception ex)
{
Globals.Log.Error(ex);
}

return new SelectList(soorten, "Value", "Text");
}


It gets called in the controller like this:

public ActionResult ManageDetail(int? id) {
var model = new MachineDetailsModel(id);
model.ChecklistOptionsOptions = sqlDal.GetChecklistOptions(model.ChecklistWaarde.SoortID);
return View("ManageDetail", model);
}


When I try to debug my code, I can see that the model values are populated correctly:


  • SoortID
    has a value of 2 (
    int
    )

  • Model.ChecklistOptionsOptions
    has a populated
    SelectLis
    t

  • Upon inspecting the
    SelectList
    I find that only item with value "2" has property
    Selected = true
    , this is
    false
    for all others.

  • When the form gets rendered, it will not select the item with value 2, rather it will have the first item selected, "Choose a value"

  • Inspecting the HTML, I see that the item with value 2 is indeed not selected, contrary to what I was expecting (see HTML below; shorted the list in count and text for readability). I expected to see "selected" on the line for item 2, as it was selected in the
    SelectList
    .





<select class="form-control" data-val="true" data-val-number="The field SoortID must be a number." data-val-required="The SoortID field is required." id="ChecklistWaarde_SoortID" name="ChecklistWaarde.SoortID" style="min-width:100%;">
<option value="">Choose a value</option>
<option value="1">Item A</option>
<option value="2">Item B</option>
<option value="3">Item C</option>
<option value="4">Item D</option>
</select>





What am I missing? How can I make item with value "2" select, as it is in the
SelectList
that I pass to the
DropDownListFor()
function?

Answer

In the controller where you are populating SelectList, set selected value there, your code would look like:

if (id.HasValue)
{
     soorten.Add(new SelectListItem 
                    { 
                      Text = reader["Naam"] as string, 
                      Value = id.Value.ToString() 
                    });
}

and then down at the line of instantiating SelectList:

return new SelectList(soorten, "Value", "Text",selectedId);

or you could elminate SelectList and instead in your model change the property ChecklistOptionsOptions type to List<SelectListItem>, in that case the last line of creating SelectList will not be required further, right now you are creating it multiple times.