Solved

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

Posted on 2008-11-03
13
448 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
  • 6
  • 6
13 Comments
 
LVL 6

Expert Comment

by:AmarIs26
Comment Utility
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
Comment Utility
public bool IsNewOrder'

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

Expert Comment

by:moseack
Comment Utility
You can use an <asp:HiddenField /> tag to hold this information.
0
 

Author Comment

by:robaherne
Comment Utility
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 500 total points
Comment Utility
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
Comment Utility
Great! Thanks a lot... that was very useful!
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:robaherne
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Turns out it was some other object instance causing the problem. It seems to work fine now... thanks a million!!!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

763 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now