Long story short, I have about 73 selectlist elements on a single page in my ASP.Net MVC web app, all made with htmlhelpers. Their contents are in json files, so I populate these select lists with typescript. However, if I do that, the selected option is never saved as the value of the element.
I found a workaround, which is to bind the model to a hidden element, add listeners to the select list elements, and assign the selected option as the value of the hidden element.
The following is the result:
@Html.HiddenFor(x => x.RFIModel.PSC, new { id = "PSC-Dropdown_Value" })
@Html.DropDownList("PSC", new SelectList(" "), new { @class = "PSC-Dropdown PSC-Dropdown_Value" })
@Html.ValidationMessageFor(x => x.RFIModel.PSC, "", new { @class = "text-danger" })
@Html.LabelFor(x => x.RFIModel.PSC)
This is working, but again, it's a workaround and its annoying when you have 72 different elements on a page. I found that is I manually define the json in SelectList(), the select list itself gets the selected value, which would be awesome, but I really want to keep my json separated from my html.
@Html.DropDownList("PSC", new SelectList("[
{ "ID": "001", "Name": "Eurasian Collared-Dove" },
{ "ID": "002", "Name": "Bald Eagle" },
{ "ID": "003", "Name": "Cooper's Hawk" },
]"), new { @class = "PSC-Dropdown PSC-Dropdown_Value" })
So with this in mind, can't I just load the json into the SelectList()?
I found a few examples here, but they aren't quite what I am looking for.
Based on a comment on the question above:
It will be client side.
Then presumably somewhere in your JavaScript code you will have a reference to your JSON data. Whether this is in the form of an object/array literal, an AJAX call, etc. doesn't really matter. At some point you would have a variable which has your data.
In that case the JSON Data example from the link you provided is what you're looking for. Specifically look at how it populates the <select>
element:
$(result).each(function() {
$("#FromJson").append($("<option></option>").val(this.ID).html(this.Name));
});
In this case result
is the variable which contains the JSON data (an array), and $('#FromJson')
is the jQuery selector to identify the <select>
element. (Yours might be something like $('#PSC')
or $('#PSC-Dropdown')
depending on your HTML and how you'd specifically identify that element.)
Basically your server-side code would render an empty list:
@Html.DropDownList("PSC", new SelectList(), new { @class = "PSC-Dropdown PSC-Dropdown_Value" })
Then in your client-side code you'd populate the value from your JSON data. The example on the link you provided uses jQuery's $().each()
, though a simple loop would do the trick too:
for (let item of result) {
$('#PSC').append($('<option/>').val(item.ID).html(item.Name));
}