?
Solved

Setting and querying page variables during AJAX postbacks in asp.net

Posted on 2008-11-03
13
Medium Priority
?
456 Views
Last Modified: 2012-05-05
I have a form that when submitted summerises the information in a table and hides the form. The idea is if the user wants to edit anything they could press a button and it'll make the form visible again so thay could alter things and re-submit.

My problem is... I need the page to know whether the form is a new submission or if the user is editing an old one.

The submit button creates an AJAX postback, which runs a button_click event in the code behind. I have some variables declared at the top of the code-behind page where I'll set 'IsNewOrder' to false. The idea being that if the user edits the form and re-posts it, the code behind will check the 'IsNewOrder' bool and behave differently to an edit than a new order.

I hope this makes sense... it seems that the AJAX postback can't access the 'IsNewOrder' variable in the code-behind. So the page thinks it's a new form submission every time. Maybe one way is to have an invisible check box in the UpdatePanel and use that to see if it's a new submission?

Is there an easier or more logical way that I'm missing?

Thanks!
0
Comment
Question by:robaherne
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
13 Comments
 
LVL 6

Expert Comment

by:AmarIs26
ID: 22866274
You need to save the variable state in ViewState. The problem is that the value of the IsNewOrder is not being stored.
note: Property typed from memory so you may need to fix syntax errors ;) if any.

public bool IsNewOrder'
{
 get
 {
   return  ViewState["IsNewOrder"] == null? false:Convert.ToBoolean(ViewState["IsNewOrder"].ToString());
 } 
 
 set
 {
   ViewState["IsNewOrder"] = value;
}
 
}

Open in new window

0
 
LVL 6

Expert Comment

by:AmarIs26
ID: 22866287
public bool IsNewOrder'

Remove the apostrophie from end. Should be
public bool IsNewOrder
0
 
LVL 7

Expert Comment

by:moseack
ID: 22866289
You can use an <asp:HiddenField /> tag to hold this information.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:robaherne
ID: 22866319
Amarls: Of course! Totally forgot about ViewStates... I'm used to using session variables though. Do you know which is better? or if it matters?
0
 
LVL 6

Accepted Solution

by:
AmarIs26 earned 2000 total points
ID: 22866479
Use ViewState because it means that your user can open the same page 10 times and the functionality will still work. But if you use session for the for visible value, then all 10 page instances will be pointing to the same session value .
So use viewstate for small flags such as these. People will say viewstate makes your page big but for storing a small value such as this, you Should be using viewstate.
I use this plugin https://addons.mozilla.org/en-US/firefox/addon/7167
to keep track of what is inside the viewstate. If viewstate starts getting too big you can use tool such as above to opitimise it.
Finally, your problem and solution is very simple so stick to that. Always wrap viewstate or Session access to a property like in my code so it is more maintanable :)
0
 

Author Closing Comment

by:robaherne
ID: 31512648
Great! Thanks a lot... that was very useful!
0
 

Author Comment

by:robaherne
ID: 22867606
Amarls,

Thanks for the answer but I'm not quite sure how to implement it!

Do I have to create an object to access the IsNewJob Accessor? If so where do I declare it?
0
 
LVL 6

Expert Comment

by:AmarIs26
ID: 22867796
No you dont need to create an object or anything, just paste that property code in your code behind.
Firstly, how are you creating the ajax call? Are you using an update panel? If so then you should simply create the property (code snippet) in your code behind file. Then what you do is you check in your code like this
if(IsNewOrder)
// show new order form
else
// hide new order form
The above should work for ajax requests as well as normal page requests (if you were not using ajax). ASP.Net ajax sends the posts the entire form to the server when you use update panels. There is virtually no difference between a normal page call and an ajax update through an update panel.
if i understand correctly, previously you had code like this
public bool IsNewOrder;
but you have to store the boolean value somewhere, so we used viewstate.  If you still need help, post your code behind file code and i will tell you where each piece of code needs to go.

public bool IsNewOrder
{
 get
 {
   return  ViewState["IsNewOrder"] == null? false:Convert.ToBoolean(ViewState["IsNewOrder"].ToString());
 } 
 
 set
 {
   ViewState["IsNewOrder"] = value;
}
 
}

Open in new window

0
 

Author Comment

by:robaherne
ID: 22867956
Amarls,

Thanks for the reply.

Yes I am using and update panel. I've done what you've suggested but I get an error - 'Object reference not set to an instance of an object.'... It's as if the IsNewOrder accessor has not been set.:

The: If(IsNewOrder){} - bit does not refer to anything yet.

Don't I have to set the initial 'value' somewhere first?

I'd then like to do this....

if(IsNewOrder)
{
     //Some bits of code here...

     IsNewOrder = false; (so that next time it will know it's not a new order)

}

Thanks again for the help!

0
 
LVL 6

Expert Comment

by:AmarIs26
ID: 22868040
you dont have to set the intial value because
ViewState["IsNewOrder"] == null? false:Convert.ToBoolean(ViewState["IsNewOrder"].ToString());
this checks if the value is null or not and returns false otherwise it will return currently assigned value.
The reason you may be getting the object not reference ... error could be that you are trying to access this property in an event where ViewState is not available. Can you post the full event code where you are using this property.
you should use it in pageload or after that because after page load the viewstate is available.
0
 

Author Comment

by:robaherne
ID: 22868145
Sure... It looks something like this
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Mono.Security;
using Npgsql;
 
public partial class Accounts_NewJob : System.Web.UI.Page
{
 
public bool IsNewJob
    {
        get
         {
           return  ViewState["IsNewOrder"] == null? false:Convert.ToBoolean(ViewState["IsNewOrder"].ToString());
         } 
         
         set
         {
           ViewState["IsNewOrder"] = value;
         }
        
    }
}
 
protected void Page_Load(object sender, EventArgs e)
    {
 
//Some bits and pieces here...
 
}
 
 
///THIS IS THE EVENT THAT GETS FIRED BY THE UPDATEPANEL
protected void Button1_Click(object sender, EventArgs e)
    { 
            if (IsNewJob)
            {
                lbl_Test.Text += "New Docket Made";
             
                // INSERT DOC
 
                // IsNewJob = false  ?????
               
            } 
               
 
            else 
            {
                lbl_Test.Text = "OLD Docket Modified";
                
                // EDIT CURRENT DOCKET
            }
 
HERE'S UPDATE PANE.....
 
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Label ID="lbl_Test" runat="server" ></asp:Label>
    </ContentTemplate>
    <Triggers>
         <asp:AsyncPostBackTrigger ControlID="ImageButton1" />
    </Triggers>
    
    </asp:UpdatePanel>

Open in new window

0
 
LVL 6

Expert Comment

by:AmarIs26
ID: 22868252
everything looks ok to me, have you stepped through the code to see which bit is null when the code is executing? Most likely the viewstate could be null but at that point it shouldnt be and also we have the null check in the get part of the property so that should take care of it.
Step through your code and see which bit is null.
 
0
 

Author Comment

by:robaherne
ID: 22868595
Turns out it was some other object instance causing the problem. It seems to work fine now... thanks a million!!!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question