views:

533

answers:

1

I've got a project were there are a number of select boxes that are loaded with reference data, ie customer types. To do this, I've create a seperate Controller that returns the data as a JSON result. This is called on page load via a jQuery function to load select list.

On submit to the customer controller, if an option has been selected but there is a validation error, the controller adds a model error message and returns to the view with the unchanged model data.

How can I get the select to keep the selected options? Ie the user selects option with value 123, when the form is returned from the post to the controller, the selected option is not "re-selected" via the jquery reload.

+2  A: 

Without seeing your code is hard to provide you with an accurate answer. However, based on what I know, I can assume that something like this will work for you:

$(function() {
   $.getJSON("/Customer/GetCustomerTypes", null, function(data) {
    //Selected CustomerType received from the Customer Controller... e.g. 123
       var selectedCustomerType = <%=selectedCustomerType %>;   
       var dropdownList = $("#customerTypeList")[0]; //Id of the dropdown  
       $.each(data, function(index, optionData) {
        var option = new Option(optionData.Text, optionData.Value);           

        if(optionData.Value == selectedCustomerType) {
      $(option).attr('selected','selected');
        }

        if ($.browser.msie) {
         dropdownList.add(option);
        }
        else {
         dropdownList.add(option, null);
        }
       });
     });
});
Jose Basilio