Wednesday, July 16, 2014

Maintining Client Side State after Server Side PostBack in ASP .net.

In ASP .net After Server Side Post Back, JavaScript Function or Content Of a readonly text Box changed By JavaScript will be lost if not maintained or re-bound.

To Get The Associated Event available for the control after post bock we need to
re-assign such events on postback

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, e) 

will do that.

Example:

 $(function () {
            MaintainSelect();
            myf();
            $("#<%= txtnetPayable.ClientID %>").attr('readonly', 'readonly');

            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, e) {
                MaintainSelect();
                myf();
                $("#<%= txtnetPayable.ClientID %>").attr('readonly', 'readonly');
            });
        });


 function MaintainSelect() {
            $(document).ready(function () {
                $('.nepali-calendar').calendarsPicker({
                    calendar: $.calendars.instance('nepali', "ne")

                });
            });
            $('#<%=dtJVDate.ClientID%>').calendarsPicker({
                calendar: $.calendars.instance('nepali', "ne"),
                onSelect: function (date) {
                    $('.nepali-calendar').val(date[0].formatDate());
                }
            });
        }


 function myf() {
            $(function () {
                $("#<%= txtDiscount.ClientID %>").change(
                         function () {
                             getamt();
                         }
                                  );

                $("#<%= txtVatAmount.ClientID %>").change(
                        function () {
                            getamt();
                            $("#<%= txtnetPayable.ClientID %>").trigger('change');
                        }
                     );
            }
            );
                }


Here, in Above Example There Are Two Cases Handled After Post Back.
1. Calendar Picker is Maintained with its popup on click.
2. A Text Box 'txtnetPayable' which needs to be Read Only and Should Display Text on change of Other Text Box.

In First Case There is not Much Trick but Reassigning Events Makes it work.

In Second Case the IF the Text Box is Made Read only in Server Side Then all the Changes on client side will be lost on server side post back.
To Eliminate this behavior we need to make text box  Read Only In client side and again we need to Maintain it Property after Server Side Post Back.