I have a page that I load a select dropdown box but I want to have javascript code toggle this list to a different set of choices.
I have the code that clears and repopulates a select list box in javascript
function UpdateDropdown(list, dropdownSelector) {
var options = '';
$.each(list, function (index, value) {
if (value.Text == null) {
value.Text = '';
}
if (value.Value == null) {
value.Value = '0';
}
options += '<option value="' + value.Value + '">' + value.Text + '</option>';
});
$(dropdownSelector).html(options);
}
so that is not the issue but my question is How can i store an array locally from my view Model to lookup later from javascript? Should i store it in a hidden select box? is there a recommended practice here?
The easiest and cleanest solution is to just write some json to your view, stored in a variable that you then access inside your UpdateDropdown function. In your view:
The exact method you use to output json will differ depending on the version of ASP.NET MVC you’re using, but that should put you on the right track.
And general javascript best practice is to create a single namespace for your code that you then put all your other variables into, so that you don’t pollute the global namespace. So really it should be something like:
But the first block of code I provided would be fine to get started with.