Question

I have a value in the DB that can be NULL and is causing me problems with Html.DropDownList. The code is stored in the DB, and is currently setting the selected value correctly.

<%= Html.DropDownList("dealerIds"
                                , new List<SelectListItem>(((List<Company.SPPC.MVC.DealerId>)ViewData["dealerIds"]).Select(i => new SelectListItem() { Value = i.Key, Text = i.Description }).ToList())
                                , new { tabloop = "", id = "ddlDealerIds" })%>

In the controller, I pull the values from an XML file and add them to the ViewData:

Dim dealerIdXmlFile As String = ConfigurationManager.AppSettings("DealerIdXmlFile").ToString()
        Using reader As System.IO.FileStream = System.IO.File.OpenRead(dealerIdXmlFile)
            Dim xmlSerializer As New System.Xml.Serialization.XmlSerializer(GetType(DealerIdModel))
            Dim dealerIdList As DealerIdModel = xmlSerializer.Deserialize(reader)
            Dim dealerIds As New List(Of DealerId)
            For Each x As DealerId In dealerIdList
                dealerIds.Add(x)
            Next
            ViewData("dealerIds") = dealerIds
        End Using

Also, the binding is explicitly set in the View:

$("#ddlDealerIds").attr("data-bind", "value: DealerId");

The issues is in two parts:

(1.) I want to add a "No ID Selected" that is the default value and will store as a NULL. I was able to get a default value in the list by adding it to the HTML.DropDownList (..., "No ID Selected"), but when I do this, the selected value is always the default, even if the record has a valid code.

I could also add it to my XML list, but then the NULL value is not matching with the XML record:

DealerId key = "" Desc="No ID Selected" ....

Also, if I view a record with valid ID, then pull up one that is NULL, the drop down stays selected to the old valid ID.

(2.) Even if adding a default value, I still want the dropdownlist to get the selected value set if there is a valid code in the DB.

I have looked at a few other posts on here, and while this seems to be common, I can't make heads or tails out of any of the solutions posted. If I add the default value, I am not getting a selected value set ever. If I fix to set the selected value, NULL values are not getting set to the default but keep the last selected DealerId value in the dropdown.

Was it helpful?

Solution

Got it to work by getting ride of the HTMLHelpers and using Knockout.JS. Set the options and everything works.

<div class="editor-field"><select id="ddlDealerIds" data-bind="options: dealerIdsList, optionsText: 'Description', optionsValue: 'Key', optionsCaption: '*** No Id Selected ***', value: DealerId"></select></div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top