We help IT Professionals succeed at work.

SaveViewState from javascript

725 Views
Last Modified: 2012-05-05
I have an aspx page containing a gridview object.  I allow row level editing in the gridview, but I handle all the edits client-side using javascript.  When all edits are done, a save button is clicked that shows an ajax modalpopupextender to confirm the save request.  The problem is that when the popup is fired, the values entered in the gridview all revert to the origin values.  I am certain that this is being caused by the viewstate process.  My question is, is there a way to invoke the documents viewstate from withiun the javascript that I am using to handle the row updates?  If not, is there another way to fix this rather annoying problem?
Thanks.
Comment
Watch Question

Christopher KileSenior Software Analyst
CERTIFIED EXPERT

Commented:
>The problem is that when the popup is fired, the values entered in the gridview all revert to the origin values.  
>I am certain that this is being caused by the viewstate process.

You are most likely incorrect - every time I went looking for a ViewState problem, I found an initialization problem instead, usually due to initializing on EVERY page refresh instead of only when IsPostBack was false.  ViewState preserves values after you change them, but mandatory refresh to original state will override the ViewState values.  Make sure your Page_Load only initializes the page if IsPostBack is false.

Author

Commented:
Thanks for the response.  The grid is only refreshed when the page is loaded. The data in the grid is updated in 2 ways.  First, the user can click an edit button on the gridrow and enter data by hand.  There are cells in the row that are replaced by calcualtions done client-side in javascript.  Secondly, the user can scan a UPC code with a barcode scanner which will activate a ajax popup panel to enter data.  In the first scenario, the datafields are handled with javascript.  In the second, a postback to the server is fired and the data is and calculations are handled server-side.  When the server-side postback is fired, only the data that has been modified in javascript reverts.  The data handled server-side is saved in the viewstate and persists.  I know this sounds strange, but it seems that I will have to do all the editing server-side so that the values persist.
Senior Software Analyst
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
I have attached the griview definition.  All the template fields are manipulated if edited. All are asp controls.  I have no problem acessing them on the server.  It's just that if I manipule row values with javascript, they are lost on the postback.  If it helps, I can put something up on the web for you to see in action.
 <asp:GridView ID="GridView1" runat="server" BorderWidth="1"   width="978px" GridLines="Both" AutoGenerateColumns="false" 
        AllowSorting="True"  DataKeyNames="branch_prod_id"  CellPadding="4" ForeColor="#333333" 
         PageSize="50">
             <Columns>
                     <asp:BoundField DataField="UPC"  HeaderText="UPC"   >
                      <HeaderStyle Cssclass="HiddenColumn" />
                       <ItemStyle Cssclass="HiddenColumn" />
                     </asp:BoundField>
                     
                     <asp:BoundField DataField="product_name" HeaderText="Product" >
                    <HeaderStyle CssClass="gridprodname" />
                     <ItemStyle CssClass="gridprodname" />
                    </asp:BoundField>
                    
                    <asp:BoundField DataField="product_desc" HeaderText="Description" >
                       <HeaderStyle CssClass="gridproddesc"/>
                       <ItemStyle CssClass="gridproddesc"/>
                       </asp:BoundField>
                       
                            <asp:BoundField DataField="all_stock"  HeaderText="In Stock" >
                            <HeaderStyle   CssClass="gridquan" />
                            <ItemStyle  CssClass="gridquan" />
                            </asp:BoundField>
                            
                              <asp:BoundField DataField="committed_stock"  HeaderText="Committed" >
                            <HeaderStyle   CssClass="gridquan" />
                            <ItemStyle  CssClass="gridquan" />
                            </asp:BoundField>
                         
                           <asp:BoundField DataField="quantity_in_stock"   HeaderText="Available" >
                            <HeaderStyle   CssClass="gridquan" />
                            <ItemStyle  CssClass="gridquan" />
                            </asp:BoundField>
                           <asp:BoundField DataField="avgcost"  HeaderText="Avg Cost" >
                            <HeaderStyle   CssClass="gridmoney" />
                            <ItemStyle  CssClass="gridmoney" />
                            </asp:BoundField>  
                            
                             <asp:TemplateField HeaderText="Value">
                            <HeaderStyle   CssClass="gridmoney" />
                            <ItemStyle  CssClass="gridmoney" />
                            <ItemTemplate>
                              
                             <asp:Label   ID="lblValue" CssClass="gridmoney" Text='<%# DataBinder.Eval(Container.DataItem, "total_value")%>' runat="server"></asp:Label>
                             
                            </ItemTemplate>
                            </asp:TemplateField>  
                        
                        <asp:BoundField DataField="UPC" HeaderText="UPC"   >
                      <HeaderStyle Cssclass="gridUPC" />
                       <ItemStyle Cssclass="gridUPC" />
                     </asp:BoundField>
                            
                       <asp:TemplateField HeaderText="New Qty">
                            <HeaderStyle CssClass="griditemquan" />
                            <ItemStyle  CssClass="griditemquan" />
                            <ItemTemplate>
                              
                             <asp:Label   ID="lblNewQuantity" CssClass="HiddenColumn" Text='<%# DataBinder.Eval(Container.DataItem, "new_quantity")%>' runat="server"></asp:Label>
                             <asp:TextBox ID="txtNewQuantity" Width="42"  CssClass="HiddenColumn" MaxLength="6" text=<%# DataBinder.Eval(Container.DataItem, "new_quantity")%> runat="server"></asp:TextBox>
                        </ItemTemplate>
                      </asp:TemplateField>  
                        <asp:TemplateField HeaderText="New Value">
                            <HeaderStyle CssClass="griditemquan" />
                            <ItemStyle  CssClass="griditemquan" />
                            <ItemTemplate>
                              
                             <asp:Label   ID="lblNewValue" CssClass="HiddenColumn" Text=<%# DataBinder.Eval(Container.DataItem, "new_value")%> runat="server"></asp:Label>
                            <asp:TextBox    ID="txtNewValue" CssClass="HiddenColumn" Text=<%# DataBinder.Eval(Container.DataItem, "new_value")%> runat="server"></asp:TextBox>
                        </ItemTemplate>
                      </asp:TemplateField>  
                       <asp:TemplateField   HeaderText="Note" >
                                     <HeaderStyle width="140px" />
                                    <ItemStyle width="140px"/>
                                    <ItemTemplate>
                                    <asp:DropDownList CssClass="HiddenColumn" ID="txtNote" runat="server">
                                     </asp:DropDownList>
                                    
                                    <asp:Label   ID="lblNote" CssClass="HiddenColumn"   Text=<%# DataBinder.Eval(Container.DataItem, "stock_note")%> runat="server"></asp:Label>
                                   
                                    </ItemTemplate>
                                </asp:TemplateField>
                       
                      <asp:TemplateField >
                                <HeaderStyle Width="56px"/>
                                <ItemStyle  Width="56px"/>
                                <ItemTemplate>
                                   <asp:Image id="btnEditItem"  runat="server" ImageUrl="images/icons/edit_16x16.gif" />
                                     <asp:Image  id="btnSaveItem"  runat="server" cssclass="HiddenColumn"  ImageUrl="images/icons/save_16x16.gif" />
                                     <asp:Image  id="btnCancelItem"  runat="server" cssclass="HiddenColumn" ImageUrl="images/icons/undo1_16x16.gif" />
                                </ItemTemplate>
                            </asp:TemplateField>
                             <asp:TemplateField  >
                                <HeaderStyle CssClass="HiddenColumn" />
                                 <ItemStyle CssClass="HiddenColumn" />
                                <ItemTemplate>
                                    <asp:TextBox ID="txtChanged" CssClass="HiddenColumn"  Text=<%# DataBinder.Eval(Container.DataItem, "changed")%>  runat="server"></asp:TextBox>
                                </ItemTemplate> 
                                 </asp:TemplateField>
                          <asp:BoundField DataField="branch_prod_id" >
                              <HeaderStyle CssClass="HiddenColumn" />
                               <ItemStyle CssClass="HiddenColumn"/>
                          </asp:BoundField>
                          <asp:BoundField DataField="prod_index_id" >
                              <HeaderStyle CssClass="HiddenColumn" />
                               <ItemStyle CssClass="HiddenColumn"/>
                          </asp:BoundField>
                </Columns>
                 <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <EditRowStyle BackColor="#999999" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
               <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                       
        </asp:GridView>

Open in new window

Christopher KileSenior Software Analyst
CERTIFIED EXPERT

Commented:
Are you performing a DataBind() on the grid every time the page loads?

Author

Commented:
No.  The databind if inside  If Not IsPostBack() .
Christopher KileSenior Software Analyst
CERTIFIED EXPERT

Commented:
What is the exact Javascript you are using to access the cell you are editing?  Other code samples are welcome if you think they are relevant, but I think I need to see the cell access code you are using.

Author

Commented:
I have attached the GridView1_RowDataBound code that sets the onclick events.  Secondly, the javascript that sets the values and changes classes that affect visiblity.  Let me know if you need more.
  If e.Row.RowType = DataControlRowType.DataRow Then
            '
 
            Dim avgcost As String = e.Row.Cells(6).Text
            Dim btnItemEdit As Image = DirectCast(e.Row.Cells(0).FindControl("btnEditItem"), Image)
            Dim btnItemSave As Image = DirectCast(e.Row.Cells(0).FindControl("btnSaveItem"), Image)
            Dim btnItemCancel As Image = DirectCast(e.Row.Cells(0).FindControl("btnCancelItem"), Image)
            'Dim imgOK As Image = DirectCast(e.Row.Cells(0).FindControl("ImageOK"), Image)
            Dim txtChanged As TextBox = DirectCast(e.Row.FindControl("txtChanged"), TextBox)
            Dim lblNewQuantity As Label = DirectCast(e.Row.FindControl("lblNewQuantity"), Label)
            Dim txtNewQuantity As TextBox = DirectCast(e.Row.FindControl("txtNewQuantity"), TextBox)
            Dim lblNote As Label = DirectCast(e.Row.FindControl("lblNote"), Label)
            'Dim txtNote As TextBox = DirectCast(e.Row.FindControl("txtNote"), TextBox)
            Dim lblNewValue As Label = DirectCast(e.Row.FindControl("lblNewValue"), Label)
            Dim txtNewValue As TextBox = DirectCast(e.Row.FindControl("txtNewValue"), TextBox)
            Dim txtNote As DropDownList = DirectCast(e.Row.FindControl("txtNote"), DropDownList)
            txtNote.DataSource = Cache("ddlreason")
            txtNote.DataValueField = "id"
            txtNote.DataTextField = "name"
            txtNote.DataBind()
            If txtChanged.Text = "1" Then
                lblNewQuantity.CssClass = "gridmoney"
                lblNote.CssClass = "griditemnote"
            End If
            txtNewQuantity.Attributes.Add("onblur", "stock_tally(" + txtNewQuantity.ClientID + "," + lblNewQuantity.Text + "," + lblNewValue.ClientID + "," + txtChanged.ClientID + "," + avgcost + ")")
            btnItemEdit.Attributes.Add("onclick", "stock_edit(" + txtNewQuantity.ClientID + "," + lblNewQuantity.ClientID + "," + lblNote.ClientID + "," + txtNote.ClientID + "," + btnItemEdit.ClientID + "," + btnItemSave.ClientID + "," + btnItemCancel.ClientID + ")")
            btnItemSave.Attributes.Add("onclick", "stock_save(" + txtNewQuantity.ClientID + "," + lblNewQuantity.ClientID + "," + lblNewValue.ClientID + "," + txtNewValue.ClientID + "," + lblNote.ClientID + "," + txtNote.ClientID + "," + btnItemEdit.ClientID + "," + btnItemSave.ClientID + "," + btnItemCancel.ClientID + "," + txtChanged.ClientID + "," + avgcost + ")")
            btnItemCancel.Attributes.Add("onclick", "stock_cancel(" + txtNewQuantity.ClientID + "," + lblNewQuantity.ClientID + "," + lblNewValue.ClientID + "," + txtNewValue.ClientID + "," + lblNote.ClientID + "," + txtNote.ClientID + "," + btnItemEdit.ClientID + "," + btnItemSave.ClientID + "," + btnItemCancel.ClientID + ")")
        End If
 
 
function stock_edit(txtnewquantity, lblnewquantity,lblnote,txtnote,btnedit,btnsave,btncancel) 
{
 
lblnote.className="HiddenColumn";
lblnewquantity.className="HiddenColumn";
if (txtnewquantity.value=="0")
  {txtnewquantity.value="";}
txtnewquantity.className="griditemquan";
txtnote.className="griditemnoteddl";
btnedit.className="HiddenColumn";
btnsave.className="gridicon";
btncancel.className="gridicon";
txtnewquantity.focus;
//var btnsubmit = document.getElementById("btnSubmit");
//var btnsuspend = document.getElementById("btnSuspend");
//btnsubmit.disabled=true;
//btnsuspend.disabled=true;
}
 
function stock_save(txtnewquantity,lblnewquantity,lblnewvalue, txtnewvalue,lblnote,txtnote,btnedit,btnsave,btncancel,txtchanged,avgcost) 
{
 
lblnewquantity.innerText=txtnewquantity.value;
lblnewvalue.innerText=Math.round(txtnewquantity.value*avgcost*100)/100
txtnewvalue.value=lblnewvalue.innerText;
var vreason= parseFloat(txtnote.value)-1;
lblnote.innerText=txtnote.children(vreason).innerText;
txtchanged.value='1';
txtnewquantity.className="HiddenColumn";
txtnote.className="HiddenColumn";
lblnewvalue.className="gridmoney";
lblnewquantity.className="griditemquan";
lblnote.className="griditemnote";
btnedit.className="gridicon";
btnsave.className="HiddenColumn";
btncancel.className="HiddenColumn";
//__doPostBack('','');
//var btnsubmit = document.getElementById("btnSubmit");
//var btnsuspend = document.getElementById("btnSuspend");
//btnsubmit.disabled=false;
//btnsuspend.disabled=false;
}
 
function stock_cancel(txtnewquantity,lblnewquantity,lblnewvalue,txtnewvalue,lblnote,txtnote,btnedit,btnsave,btncancel) 
{
txtnewquantity.value=lblnewquantity.innerText;
txtnote.value=lblnote.innerText;
txtnewquantity.className="HiddenColumn";
lblnewvalue.innerText =txtnewvalue.value;
 
if (lblnewquantity.innerText=="0")
    {lblnewquantity.className="HiddenColumn";
    lblnewvalue.className="HiddenColumn";
    }
else
    {lblnewquantity.className="griditemquan";
     lblnewvalue.className="griditemquan";
    }
txtnote.className="HiddenColumn";
lblnote.className="griditemnote";
btnedit.className="gridicon";
btnsave.className="HiddenColumn";
btncancel.className="HiddenColumn";
//var btnsubmit = document.getElementById("btnSubmit");
//var btnsuspend = document.getElementById("btnSuspend");
//btnsubmit.disabled=false;
//btnsuspend.disabled=false;
}
 
function stock_tally( txtnewquan,OriginalValue,lblnewvalue,changed,avgcost) 
{
    var vnewquan = parseFloat(txtnewquan.innerText);
 
    if (IsNumeric(txtnewquan.value)==false)
    {
        alert("New Quantity must be a number");
        txtnewquan.value=OriginalValue;
        txtnewquan.focus;
    }
    else
    {
    if (txtnewquan.value !=='')
    {
    lblnewvalue.innerText=Math.round(txtnewquan.value*avgcost*100)/100;
    lblnewvalue.className="gridmoney";
    changed.value='1';
    }
    }
    
        function IsNumeric(sText)
        {
           var ValidChars = "0123456789.";
           var IsNumber=true;
           var Char;
 
         
           for (i = 0; i < sText.length && IsNumber == true; i++) 
              { 
              Char = sText.charAt(i); 
              if (ValidChars.indexOf(Char) == -1) 
                 {
                 IsNumber = false;
                 }
              }
          
           return IsNumber;
           
        }
 
  
}

Open in new window

Author

Commented:
Good morning, cpkilekofp,
I have found the error in my code.  When updating a asp:Label component in javascript, there is to .value property as there is with a TextBox.  So, to make it work, I was updating the innerText property of the Label components.  However, when the postback occured, all the label components were being rendered with the Text property which had not been modified in the javascript.  I put some code in to correct this at postback, so all is good now.  I am awarding you the points because your questions and comments led me to the answer.  Many thanks for you help!

Author

Commented:
Thanks again for your help.
Christopher KileSenior Software Analyst
CERTIFIED EXPERT

Commented:
*nods* :) Glad to help, and yes, it is exactly this sort of thing I was hoping to get you to look at.  "The Devil is in the details."  
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.