Thursday, 24 March 2016

Set DropdownList Selected Value from Hidden Field

Aim :- Set DropdownList Selected Value from Hidden Field. I have added complexity that the dropdownlist id is dynamically generated as it may be necessary to generate the same controls in the page multiple times.

So let’s see what we have here.

Partial view Page
Part of the view content will come from a Partial Page. The Partial Page may be called multiple times (repeated in main view). Hence the hidden field has id/name generated dynamically

@Html.Hidden("SelectedCls"+session.Recipient.RecipientId.ToString(), selectedClass.ClassId)

View Page
The Dropdownlist may be also generated multiple times, hence id is partially generated dynamically.
@Html.DropDownList("TempClsId",new SelectList(Model.ViewOnlyClassRoomList, "Id", "Name"),new { @class = "roomClassStyle", id = String.Format("TempClsId {0}", uniqueId), style = "width: 260px" })

We need to set the selected value in the dropdownlist once the page load is completed. Hence our code will be set inside document.ready. We are using two loops here, they are not necessary in case we have only one dropdownlist. Here, first we are fetching all the dropdownlist which has TempClsId preceding its name. Once all the dropdownlists are fetched in an array, we look for hidden fields which has name starting with SelectedCls and the ID which is common for both the dropdownlist & the hiddenfield. The selected value is set to the hidden field value at the next step.

<script type="text/javascript">
     $(document).ready(function () {
         var retval = []
         $("select[name^='TempClsId']").each(function () {
         for (var i = 0; i < retval.length; i++) {            
             var selcls = 'SelectedCls' + retval[i].replace('TempClsId', '');
             var selval = $('input[name^=' + selcls + ']').attr('value');            
             $('#' + retval[i]).val(selval);